How to add a hook for password under user.ts

default discord avatar
clhome
4 weeks ago
1 2

I need to determine whether the password strength meets the requirements when the user sets or changes the password. How can I set it up?
I can`t find password in user.ts,
How to add a hook for password under user.ts

  • discord user avatar
    DanRibbens
    Payload Team
    3 weeks ago

    @clhome
    Here is a code example for you:

    /**
     * Throws error if password strength is not met. Password must have:
     *  - 8 or more characters
     *  - uppercase and lowercase letters
     *  - at least one symbol
    **/
    const validatePassword: CollectionBeforeValidateHook = ({ data: { password } }) => {
      let message: string;
      if (password.length <= 8) message = 'Password must be at least 8 characters long';
    
      const hasUpperCase = /[A-Z]/.test(password);
      const hasLowerCase = /[a-z]/.test(password);
      if (!hasUpperCase || !hasLowerCase) message = 'Password must have both uppercase and lowercase letters')
    
      const hasSymbols = /[$-/:-?{-~!"^_`\[\]]/.test(password);
      if (!hasSymbols) message = 'Password must include at least one symbol.'
    
      if (message) throw new ValidationError([{ message, field: 'password'}]);
    };
    
    // if you don't have a users collection already you need to make one to set the beforeValidate hook:
    const Users: CollectionConfig = {
      slug: 'users',
      auth: true,
      hooks: {
        beforeValidate: [validatePassword],
      },
      fields: [],
    }
    1 reply
  • default discord avatar
    clhome
    3 weeks ago

    Thank you very much, The problem has been resolved.

  • discord user avatar
    DanRibbens
    Payload Team
    4 weeks ago

    Great question!
    This has to be done in a beforeValidate function on the auth collection.

    1 reply
    default discord avatar
    clhome
    4 weeks ago

    sorry,I don't understand where to write beforeValidate , can you give me an example, thank you.

Open the post
Continue the discussion in GitHub
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.