#multiple form validation [SOLVED]
15 messages · Page 1 of 1 (latest)
validate: (values) => ({
username: [
values.username.length < 3 ? 'Username is too short' : null,
usernames.includes(values.username) ? "Username already exists" : null,
],
// email: (/^\S+@\S+$/.test(values.email) ? null : 'Invalid email'),
})
when both of the validation is correct, the box still becomes red
i tried changing the null value to string, and i've confirmed the null makes the box error
this is definitely because of multiple validations
but idk how to fix this
The field is considered in error as soon as the value returned by validate for the given field is not null. In this case, when all is good you return [null, null], which is not null and is considered as an error by useForm.
If you want to store your validation as an array like that, you need to return the array only if at least one element is not null, and return null otherwise.
You can create a helper function for this:
function multiValidation(rules: unknown[]) {
const allNull = rules.reduce((acc, rule) => acc ?? rule, null)
return allNull ? null : rules
}
Then you can use it in your validation function:
validate: (values) => ({
username: multiValidation([
values.username.length < 3 ? 'Username is too short' : null,
usernames.includes(values.username) ? "Username already exists" : null,
]),
})
ahh i see
i'll test this out
tysm it works! though i had to change the return to
return allNull ? rules : null;
Ah yeah my bad, the reduce is inverted, I meant to add a ! in front of it.
ah i see
btw i have another question, should i make another post or can i just ask it here?
nvm i created a new post https://discord.com/channels/854810300876062770/1046017563248832522