简体   繁体   English

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

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

I'm using react-hook-form with yup validation and MUI components in my react TypeScript app.我在我的 react TypeScript 应用程序中使用带有 yup 验证和 MUI 组件的 react-hook-form。 The errors from the yup validation is showed only after the user is trying to submit the form (clicking on the submit button). yup 验证的错误仅在用户尝试提交表单(单击提交按钮)后显示。 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>
)

Look at the component from 'react-hook-form'查看来自“react-hook-form”的组件

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

You can set the validation mode to onChange inside the useForm function. This way, every time the user types, the validation will get executed.您可以在useForm function 中将验证模式设置为onChange 。这样,每次用户键入时,都会执行验证。

More info here: UseForm - React Hook Form此处提供更多信息: 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.相反,如果您想随时验证字段,而不是在用户更改输入时验证字段,则可以使用 React Hook Form 中的触发器 function

Feel free to ask anything else!随时问任何其他问题!

-Ado -阿多

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

相关问题 如何使用带有react-hook-form的yup验证模式跳过对fieldArray表单中最后一个object的验证? - How to skip validation for last object in fieldArray form using yup validation schema with react-hook-form? 在 Yup Validation React-Hook-Form 中添加了 2 个 Schema - Added 2 Schema in Yup Validation React-Hook-Form 如何以编程方式触发“react-hook-form”中字段的验证? - How to programmatically trigger validation on a field in 'react-hook-form'? 如何使用 react-hook-form 有条件地禁用提交按钮? - How to conditionally disable the submit button with react-hook-form? 如何在“react-hook-form”库中的控制器组件中使用 Yup 验证模式 - How to use Yup validation schema with the Controller component in `react-hook-form` lib 如何使用 React-hook-form 验证 React-quill? - How to validate React-quill with React-hook-form and yup? 如何将 yup validationSchema 与 react-hook-form 一起使用? - How can I use yup validationSchema with react-hook-form? 如何以 react-hook-form 触发解析器 - How to trigger resolver in react-hook-form 如何在 react-hook-form 中进行验证? - How to make a validation in react-hook-form? 使用和 react-hook-form 进行 React yup 验证,不同类型对象的数组取决于 object 属性之一 - React yup validation with and react-hook-form, array of different type of objects depends from one of object attribute
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM