If I click on the email input field, the field says "Enter Your Email". This was set by me. However, during I'm typing,when the validation check isn't fulfilled, it says 'enter a valid email' something, which is a default, not written by me.
In case of wrong password, since I am using .matches(), I get my desired text printed on the screen. How can I do so for email as well?
Here's my Yup object:
const schema = Yup.object({
email: Yup
.string()
.email()
.required('Please Enter your Email'),
password: Yup
.string()
.required('Please Enter your password')
.matches(
/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/,
"Must Contain 8 Characters, One Uppercase, One Lowercase, One Number and one special case Character"
)
});
This is how my Formik component looks like:
<Formik
initialValues={{ email: '', password: '' }}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
validationSchema={schema}
>
{props => {
const {
values: { email, password },
errors,
touched,
handleChange,
isValid,
setFieldTouched
} = props;
const change = (name: string, e: { persist: () => void; }) => {
e.persist();
handleChange(e);
setFieldTouched(name, true, false);
};
return (
<form style={{ width: '100%' }} onSubmit={_ => alert('Submitted!')}>
<TextField
variant="outlined"
margin="normal"
id="email"
fullWidth
name="email"
helperText={touched.email ? errors.email : ""}
error={touched.email && Boolean(errors.email)}
label="Email"
value={email}
onChange={change.bind(null, "email")}
/>
<TextField
variant="outlined"
margin="normal"
fullWidth
id="password"
name="password"
helperText={touched.password ? errors.password : ""}
error={touched.password && Boolean(errors.password)}
label="Password"
type="password"
value={password}
onChange={change.bind(null, "password")}
/>
</Formik>
In Formik props, errors : An object containing error messages of the field.
I found that the accepted answer is correct but can be incomplete in some cases. Placing the cursor into a field and tabbing out of it can trigger a Yup "type error".
A default Yup type error is a verbose and non-user-friendly thing ;)
I would extend the answer from AndreasT to read:
email: Yup
.string()
.email('this will be displayed when email is wrong')
.required('this will be displayed when empty')
.typeError('A number is required')
Here is the article that turned me on to this answer.
add your preferred error string to your email schema:
email: Yup
.string()
.email('this will be displayed when email is wrong')
.required('this will be displayed when empty')
codesandbox example: https://codesandbox.io/s/blissful-shape-lijo2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With