Formik通过React和Material UI处理复选框验证



我正在尝试处理";接受服务条款";带有React和Material UI的复选框。

到目前为止,我做到了:

验证架构

const validationSchema = yup.object().shape({
email: yup
.string()
.email('Enter a valid email address')
.required('Email address is required'),
password: yup
.string()
.min(8, 'Password should be of minimum 8 characters')
.required(),
termsOfService: yup
.boolean()
.required('You must accept the Terms of Service to proceed')
.oneOf([true], 'Error')
})

表单组件

const formik = useFormik({
initialValues: {
email: '',
password: '',
termsOfService: false
},
validationSchema,
onSubmit: async values => {
alert(JSON.stringify(values, null, 2))
}
})

表单组件JSX

<Box
component="form"
noValidate
onSubmit={formik.handleSubmit}
sx={{ mt: 1 }}
>
<TextField
autoFocus
margin="normal"
required
fullWidth
id="email"
label={t('email_address')}
name="email"
autoComplete="email"
value={formik.values.email}
onChange={formik.handleChange}
error={formik.touched.email && Boolean(formik.errors.email)}
helperText={formik.touched.email && formik.errors.email}
/>
<TextField
margin="normal"
required
fullWidth
name="password"
label={t('password')}
type="password"
id="password"
autoComplete="current-password"
value={formik.values.password}
onChange={formik.handleChange}
error={formik.touched.password && Boolean(formik.errors.password)}
helperText={formik.touched.password && formik.errors.password}
/>
<FormControlLabel
control={<Checkbox value="terms-of-service" color="primary" />}
label={t('terms_of_service')}
/>
<Button type="submit" fullWidth variant="contained" sx={{ mt: 3, mb: 2 }}>
{t('sign_up_button')}
</Button>
</Box>

如何做到这一点,以同样的方式,我管理文本输入的验证?

检查此示例

您可以在复选框的onChange事件中使用formik.setFieldValue来设置复选框值。此外,使用muiFormHelperText显示验证错误。

<FormControl>
<FormControlLabel
control={
<Checkbox
onChange={(e) => { setFieldValue("termsOfService", e.target.checked) }}
name="termsOfService"
checked={values.termsOfService}
/>
}
label="terms_of_service"
>
<FormHelperText style={{ color: "red" }}>
{touched.termsOfService && errors.termsOfService
? touched.termsOfService && errors.termsOfService
: " "}
</FormHelperText>
</FormControl>

最新更新