简体   繁体   中英

Formik handle checkbox validation with React and Material UI

I'm trying to handle the Checkbox validation for an "Accept Terms of Service" checkbox with React and Material UI.

So far I did this:

Validation Schema

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

Form Component

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

Form Component 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>

How to do that, in the same way, I managed the validation on the text inputs?

Check this example

You can use formik.setFieldValue inside onChange event of checkbox to set checkbox value. Also, use mui FormHelperText to show validation error.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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