I have the follow Yup configuration in my React app:
const schema = yup.object().shape({
email: yup.string()
.email('E-mail is not valid!')
.required('E-mail is required!'),
password: yup.string()
.min(6, 'Password has to be longer than 6 characters!')
.required('Password is required!'),
tandc: yup.boolean()
.oneOf([true], "You must accept the terms and conditions")
})
My form looks like this (using Formik):
<Form>
<div className="form-group">
<label >Email
<Field type="email" name="email" className="form-control" />
</label>
<ErrorMessage name="email" component="div" className="invalid-feedback" />
</div>
<div className="form-group">
<label >Password
<Field type="password" name="password" className="form-control" />
</label>
<ErrorMessage name="password" component="div" className="invalid-feedback" />
</div>
<div className="form-group">
<Field type="checkbox" name="tandc" className="form-check-input" id="tandc" />
<ErrorMessage name="tandc" component="div" className="invalid-feedback" />
<label htmlFor="tandc" >I agree to the Terms and Conditions
</label>
</div>
<PrimaryButton label="Login" disabled={isSubmitting} type="submit">
Submit
</PrimaryButton>
</Form>
If the user clicks submit on the form, Yup validates the email and password field but ignores the checkbox field:
I can only get the checkbox validation to work if I first check and then uncheck the terms and conditions.
How do I make it work so that it shows the error message when the user clicks just the submit button?
According to this issue in Yup repository,
if you're using it with formik make sure you set
initialValues = {termsOfService: false}