Home > database >  How to trigger yup validation in react-hook-form before the user is clicking the submit button?
How to trigger yup validation in react-hook-form before the user is clicking the submit button?

Time:01-31

I'm using react-hook-form with yup validation and MUI components in my react TypeScript app. The errors from the yup validation is showed only after the user is trying to submit the form (clicking on the submit button). I want the user to see the fields errors before the submit.

Thank you all!

Yup schema:

export default function signUpSchema(existingUsernames: string[]) {
return yup.object().shape({
    firstName: yup
        .string()
        .required('First name is a required field')
        .matches(/^\S*$/, 'No whitespaces allowed')
        .matches(/^[^\d] $/, 'No numbers allowed')
        .max(20, 'First name must be at most 20 characters'),
    lastName: yup
        .string()
        .required('Last name is a required field')
        .matches(/^\S*$/, 'No whitespaces allowed')
        .matches(/^[^\d] $/, 'No numbers allowed')
        .max(20, 'Last name must be at most 20 characters'),
    username: yup
        .string()
        .required('Username is a required field')
        .matches(/^\S*$/, 'No whitespaces allowed')
        .max(20, 'Username must be at most 20 characters')
        .notOneOf(existingUsernames, 'Username already taken'),
    password: yup
        .string()
        .required('Password is a required field')
        .min(4, 'Password must be at least 4 characters')
        .matches(/^\S*$/, 'No whitespaces allowed')
        .max(20, 'Password must be at most 20 characters'),
})

}

SignUpForm:

const {
    register,
    handleSubmit,
    formState: { errors, isValid },
} = useForm<SignUpFormValues>({
    resolver: yupResolver(signUpSchema(data ? data.usernames : [])),
})

return (
    <Container>
        <Typography>Sign up to NoStress</Typography>

        <form onSubmit={handleSubmit(onSubmit)}>
            <TextField
                label="First Name"
                {...register('firstName')}
                error={Boolean(errors.firstName)}
                helperText={errors.firstName ? errors.firstName.message : ''}
            />
            <br />
            <TextField
                label="Last Name"
                {...register('lastName')}
                error={Boolean(errors.lastName)}
                helperText={errors.lastName ? errors.lastName.message : ''}
            />
            <br />
            <TextField
                label="Username"
                {...register('username')}
                error={Boolean(errors.username)}
                helperText={errors.username ? errors.username.message : ''}
            />
            <br />
            <TextField
                label="Password"
                type={showPassword ? 'text' : 'password'}
                {...register('password')}
                error={Boolean(errors.password)}
                helperText={errors.password ? errors.password.message : ''}
                InputProps={{
                    endAdornment: (
                        <InputAdornment position="end">
                            <IconButton onClick={togglePasswordVisibility}>
                                {showPassword ? (
                                    <VisibilityOff />
                                ) : (
                                    <Visibility />
                                )}
                            </IconButton>
                        </InputAdornment>
                    ),
                }}
            />
            <br />
            <Link href="/signin">
                <Typography>Already have an account? Sign in.</Typography>
            </Link>
            <Button type="submit" variant="contained" disabled={!isValid}>
                Sign Up
            </Button>
        </form>
    </Container>
)

CodePudding user response:

Look at the component from 'react-hook-form'

read about that: https://react-hook-form.com/api/usecontroller/controller

CodePudding user response:

You can set the validation mode to onChange inside the useForm function. This way, every time the user types, the validation will get executed.

More info here: UseForm - React Hook Form

If instead you want to validate the fields whenever you want, and not when the user changes the input, you can use the trigger function from React Hook Form.

Feel free to ask anything else!

-Ado

  • Related