How to add a hook for password under user.ts #2615
-
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? |
Beta Was this translation helpful? Give feedback.
Answered by
DanRibbens
May 5, 2023
Replies: 2 comments 4 replies
-
Great question! |
Beta Was this translation helpful? Give feedback.
1 reply
-
@clhome /**
* 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: [],
} |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
clhome
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@clhome
Here is a code example for you: