I am trying to validate a material ui form using Formik and Yup but I am getting an error.
This is my schema that I import from another file.
export const schema = Yup.object({
email: Yup.string()
.email('Invalid Email')
.required('This Field is Required'),
});
This is where I am using the validation.
If I write validation = schema
it didn't give an error but there was no validation either. If I change it to {schema}
the app crashes.
export default function RemoveUserPage() {
const [isSubmitted, setIsSubmitted] = useState(false);
const [isRemoved, setIsRemoved] = useState(false);
const [errorMessage, setErrorMessage] = useState('');
const [removeUser] = useMutation(REMOVE_USER);
let submitForm = (email: string) => {
setIsSubmitted(true);
removeUser({
variables: {
email: email,
},
})
};
const formik = useFormik({
initialValues:{ email: '' },
onSubmit:(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
},
validationSchema:{schema}
})
const handleChange = (e: ChangeEvent<HTMLInputElement>)=>{
const {name,value} = e.target;
formik.setFieldValue(name,value);
}
return (
<div>
<Form
onSubmit={e => {
e.preventDefault();
submitForm(formik.values.email);
}}>
<div>
<TextField
variant="outlined"
margin="normal"
id="email"
name="email"
helperText={formik.touched.email ? formik.errors.email : ''}
error={formik.touched.email && Boolean(formik.errors.email)}
label="Email"
value={formik.values.email}
//onChange={change.bind(null, 'email')}
onChange={formik.handleChange}
/>
<br></br>
<CustomButton
disabled={!formik.values.email}
text={'Remove User'}
/>
</div>
</Form>
</div>
);
}
Additionally, I also want to pass isValid!
condition in the disabled
of the button but I can't figure out how to do so. I got it in since I could write it in the props but not sure how to use it in useFormik().
Also, when I submit the form, it the text-fields aren't reset automatically. How could I fix that?
Error:
TypeError: schema[sync ? 'validateSync' : 'validate'] is not a function. (In 'schema[sync ? 'validateSync' : 'validate'](validateData, {
abortEarly: false,
context: context
})', 'schema[sync ? 'validateSync' : 'validate']' is undefined)
Earlier on, I was using <Formik>
. In this case, the validation was done while I was typing, for instance if I write 'hfs' it will tell me invalid email immediately while I am typing. However, with useFormik (acc to the answer below), it says invalid email only after I submit the form. I don't want to happen because once the form is submitted, the mutation is called as well. I want to keep the validation separate. This is what I was using earlier
export default function RemoveUserPage() {
const [isSubmitted, setIsSubmitted] = useState(false);
const [isRemoved, setIsRemoved] = useState(false);
const [errorMessage, setErrorMessage] = useState('');
const [removeUser] = useMutation<DeleteUserResponse>(REMOVE_USER);
let submitForm = (email: string) => {
setIsSubmitted(true);
removeUser({
variables: {
email: email,
},
})
.then(({ data }: ExecutionResult<DeleteUserResponse>) => {
if (data !== null && data !== undefined) {
setIsRemoved(true);
}
})
};
return (
<div>
<Formik
initialValues={{ email: '' }}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
validationSchema={schema}>
{props => {
const {
values: { email },
errors,
touched,
handleChange,
isValid,
setFieldTouched,
} = props;
const change = (name: string, e: FormEvent) => {
e.persist();
handleChange(e);
setFieldTouched(name, true, false);
};
return (
<Wrapper>
<Form
onSubmit={e => {
e.preventDefault();
submitForm(email);
}}>
<div>
<TextField
variant="outlined"
margin="normal"
id="email"
name="email"
helperText={touched.email ? errors.email : ''}
error={touched.email && Boolean(errors.email)}
label="Email"
value={email}
onChange={change.bind(null, 'email')}
/>
<br></br>
<CustomButton
disabled={!isValid || !email}
text={'Remove User'}
/>
</div>
</Form>
);
}}
</Formik>
</div>
);
}
It should be validationSchema: schema instead of {schema}
The reason why it doesn't validate is that you don't use formik's handleSubmit
useFormik({
initialValues:{ email: '' },
onSubmit:(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
},
validationSchema: schema
})
...
<Form onSubmit={formik.handleSubmit}>
...
<CustomButton
disabled={formik.touched.email && formik.errors.email ? true : false}
text={'Remove User'}
/>
...
</Form>
It should use formik's handleSubmit to get the validation what you define on validationSchema
Also pass the formik.touched.email && formik.errors.email to disabled prop of the button.
Based on your request, to validate the field when you type, you should do as the following:
<TextField
variant="outlined"
margin="normal"
id="email"
name="email"
helperText={formik.touched.email ? formik.errors.email : ""}
error={formik.touched.email && Boolean(formik.errors.email)}
label="Email"
value={formik.values.email}
onChange={props => {
formik.handleChange(props);
formik.handleBlur(props);
}}
onBlur={formik.handleBlur}
/>