我在react TypeScript应用中使用react-hook-form和yup验证以及MUI组件。yup验证的错误只有在用户尝试提交表单(点击提交按钮)后才会显示。我希望用户在提交前看到字段错误。
谢谢大家!
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>
)
1条答案
按热度按时间m1m5dgzv1#
您可以在
useForm
函数中将验证模式设置为onChange
,这样,每次用户键入时,验证都会执行。更多信息:UseForm - React Hook Form
相反,如果您希望在任何时候验证字段,而不是在用户更改输入时验证字段,则可以使用React Hook Form中的trigger function。
有什么问题尽管问!