#multiple form validation [SOLVED]

15 messages · Page 1 of 1 (latest)

topaz leaf
#

how do i add multiple validation for form? i want to validate if the username exists and if the username is more than 3 characters

#
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

fathom raft
#

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,
            ]),
        })
topaz leaf
#

ahh i see

#

i'll test this out

#

tysm it works! though i had to change the return to

return allNull ? rules : null;
fathom raft
#

Ah yeah my bad, the reduce is inverted, I meant to add a ! in front of it.

topaz leaf
#

ah i see

topaz leaf