Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Role validation

default discord avatar
shisuelast year
4

Hi,



I'm creating the user roles, and I want to make the role of organization Manager require the field organization to be filled.



I am currently using validate on the organization field, such that I check if the role organizationMember was added or not. The issue is, the value is checked against the "current" state of user, such that I am able to add the role organizationMember without failing the check, but after the role being added, the check starts working and requesting the field organization to be filled.



I want to make it so the role cannot be added unless the field is filled.



{ name: 'organization', label: 'Organization', type: 'text', validate: (value, { user }) => { console.log(user) if (user?.roles.includes('organizationManager') || user?.roles.includes('organizationMember')) { return value ? true : 'Please provide a value' } return true; }, // relationTo: 'organizations', // hasMany: false, },
  • default discord avatar
    superwafflepuffslast year

    what does your roles field look like?



    if it's a select you can use

    filterOptions
  • default discord avatar
    shisuelast year

    Yea it is, it looks like this:



    { name: 'roles', label: 'Roles', type: 'select', hasMany: true, defaultValue: ['user'], options: [ { label: 'User', value: 'user', }, { label: 'Admin', value: 'admin', }, { label: 'Organization Manager', value: 'organizationManager', }, { label: 'Organization Member', value: 'organizationMember', }, { label: 'Funder', value: 'funder', }, { label: 'Facilitator', value: 'facilitator', } ], access: { read: () => true, update: () => true, create: () => true, }, saveToJWT: true, hooks: { beforeChange: [protectRoles], }, },
  • default discord avatar
    superwafflepuffslast year

    I think you can move your validation to the roles field in your user object



    {
      name: 'roles',
      type: 'relationship',
      relationTo: 'roles',
      hasMany: true,
      validate (val, { data }) {
        if (val.includes('organizationManager') && !data.organization.length) {
          return 'You must provide an Organization Name to use the Organization Manager Role';
        }
        return true;
      }
    }


    something like that (not tested)

  • default discord avatar
    shisuelast year

    Thanks! That logic worked

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team..