繁体   English   中英

如何在用户单击提交按钮之前以 react-hook-form 触发 yup 验证?

[英]How to trigger yup validation in react-hook-form before the user is clicking the submit button?

我在我的 react TypeScript 应用程序中使用带有 yup 验证和 MUI 组件的 react-hook-form。 yup 验证的错误仅在用户尝试提交表单(单击提交按钮)后显示。 我希望用户在提交之前看到字段错误。

谢谢你们!

是的架构:

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'),
})

}

注册表格:

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>
)

查看来自“react-hook-form”的组件

阅读相关内容: https://react-hook-form.com/api/usecontroller/controller

您可以在useForm function 中将验证模式设置为onChange 。这样,每次用户键入时,都会执行验证。

此处提供更多信息: UseForm - React Hook Form

相反,如果您想随时验证字段,而不是在用户更改输入时验证字段,则可以使用 React Hook Form 中的触发器 function

随时问任何其他问题!

-阿多

①如果本文未解决您的问题,请点击查看与本文相关的问题
②如果本文未解决您的问题,请向程序员专用AI小助手提问
暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM