0
votes

I am using Formik and Yup, when I pre-populate a field/form Yup validates the fields as if they aren't populated. I have the basic CRUD type layout where updating data requires the form to be pre-populated. Those pre-populated fields shouldn't be validating with an error. What am I doing wrong?

Validation Schema:

const validationSchema = Yup.object({
fname: Yup
    .string()
    .required('First Name is required'),
lname: Yup
    .string()
    .required('Last Name is required'),
address: Yup
    .string()
    .required('Address is required'),
city: Yup
    .string()
    .required('City is required'),
});

Formik:

const formik = useFormik({
    initialValues: {
        fname: '',
        lname: '',
        address: '',
        city: '',
    },
    validationSchema: validationSchema,
    onSubmit: values => {
        alert(JSON.stringify(values, null, 2));
    },
});

Example field:

<TextField
    id="fname"
    name="fname"
    variant="outlined"
    value={location.fname}
    onChange={formik.handleChange}
    error={Boolean(formik.errors.fname)}
    helperText={formik.errors.fname} />
1

1 Answers

0
votes

I needed to set the initalValues...

const formik = useFormik({
    initialValues: {
        fname: props.fname,
        lname: props.lname,
        address: props.address,
        city: props.city,
    },
    validationSchema: validationSchema,
    onSubmit: values => {
        alert(JSON.stringify(values, null, 2));
    },
});