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
@gycsabesz When submitting the email to the forgot-password endpoint I'd get 'Cannot read properties of undefined: length', so i figured that the validation should only be done IF there IS a password in the req whatsoever:
//Checking if a password was submitted before attempting to check its length
if (password && password.length <= 8) message = <YOUR_MESSAGE>
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.
I'd be curious how to approach this in Payload V3. When I've been migrating the error no longer shows the message in the UI
Star
Discord
online
Get dedicated engineering support directly from the Payload team.