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
@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: [],
}
Thank you very much, The problem has been resolved.
@DanRibbens this won't get triggered before reset password API call (/api/[collection-slug]/reset-password
). Moreover, it seems like none of the hooks gets triggered in that case. :( Any idea how to overcome this?
Payload CMS version: 1.10.4
Great question!
This has to be done in a beforeValidate
function on the auth collection.
sorry,I don't understand where to write beforeValidate
, can you give me an example, thank you.
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.