I am using useformik hook on my page along with yup to display validations. I have a custom component using formik values and has a validation definition on yup validationSchema. the error message is displaying only once either on Tab or submit.
const validationSchema = yup.object().shape({
message: yup
.string()
.when(["category"], {
is: (category) =>
category !== CATEGORY_CANDIDATE_EMAIL.toString(),
then: yup
.string()
.matches(/RELATED.LINK/, "the RELATED.LINK text is required" ),
})
.required("error message required message")
.nullable()
.trim(),
category: yup
.string()
.required("error message required category")
.nullable()
.trim(),
});
<CustomInput
id="message"
name="message"
value={formik.values.message}
bodyText={messageTextLocalized}
readonly={false}
previewModeError={false}
placeHolderText={msgEnterEmailTemplatemessageTextLocalized}
onChange={(e) => {
handleChange({ target: { name: "message", value: e } });
setCustomValidation({
...customValidation,
message:
e.indexOf("RELATED.LINK") === -1 &&
formik.values.category !==
`${CATEGORY_CANDIDATE_EMAIL}`,
});
}}
hasError={
customValidation.message ||
((formik.errors.message && formik.touched.message) as boolean)
}
errorMessage={formik.errors.message || ""}
/>
I tried to add another <ErrorMessage /> field to display but it is now displaying same error message twice. can anyone please help me identify what can be done here.
Related
I`ve got this yup schema:
`const ModalEditCard = () => {
const validationSchema = Yup.object().shape({
title: Yup.string()
.required("Поле обязательно для заполнения")
.max(50, "Заголовок не более 50 символов")
});`
React-hook-form options:
const {
register,
handleSubmit,
formState: { errors, isValid }
} = useForm<UserSubmitForm>({
resolver: yupResolver(validationSchema),
mode: "onSubmit",
reValidateMode: "onChange",
});
and this textarea:
` <textarea
{...register(name)}
rows={1}
className="modal__textArea"
placeholder={placeholder}
/>`
I whant to show how mach symbols user has to write. Example I have max 50 symbols for textarea. If I write hello, under field i want to see "45". And it`s should be just message. Not validate
I had custom hook for count symbols. But i think, Yup could help me
I am having great difficulty trying to get the error text to appear below my mui checkbox when I yarn dev my signup form. Below is a snippet of the jsx code I used.
``` <FormControlLabel
control={<Checkbox checked={formik.values.termsAndConditions}/>}
label={
<TermsTypography>
I accept the terms and conditions
</TermsTypography>
}
name="termsAndConditions"
onChange={formik.handleChange}
/>```
ValidationSchema:
```const validationSchema = Yup.object({
username: Yup
.string()
.required('Username is required')
.min(8, 'Username should be a minimum of 8 characters in length')
.max(30, 'Username should not exceed 30 characters in length'),
email: Yup
.string()
.email('Enter a valid email')
.required('Email is required'),
password: Yup
.string()
.required('Password is required')
.matches(/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/, 'Password must have at least one letter and number and a minimum of 8 characters')
.min(8, 'Password should be of minimum 8 characters length')
.max(30, 'Password should not exceed 30 characters in length'),
confirmPassword: Yup
.string()
.oneOf([Yup.ref('password'), null], 'Passwords must match'),
termsAndConditions: Yup
.bool()
.oneOf([true], 'You must accept the terms and conditions')
});```
const formik:
```const formik = useFormik({
initialValues: {
username: '',
email: '',
password: '',
confirmPassword: '',
termsAndConditions: false
},
validationSchema: validationSchema,
onSubmit: (values) => {
console.log(values);
setIsLoading(true);
},
});```
I don't think there is an error in my validation Schema or in my formik. From what I have gathered elsewhere on stackoverflow the checkbox is rather tricky. Perhaps the way I am using label for my FormControlLabel is what is causing the issue? I also have my formik and Yup imports imported properly or else my other jsx elements like user name and password would not be showing any error handling. So what am I doing wrong here?
This is my default value:
const defaultValues = {
busi_day: [],
busi_start_time: '09:00',
busi_end_time: '17:00',
};
This is my 2 fields:
<FastField type="time" className="start-time" name="busi_start_time" value={values.busi_start_time} />
<FastField type="time" className="start-time" name="busi_end_time" value={values.busi_end_time} />
This is my validatio using Yup:
const validationSchema = Yup.object().shape({
busi_start_time: Yup.string()
.required(),
busi_end_time: Yup.string()
.required(),
});
Now, I want to validate that the busi_end_time must be after the busi_start_time. For example:
{busi_start_time: '09:00' busi_end_time: '17:00'} is valid but {busi_start_time: '14:00' busi_end_time: '08:00'} is not valid. How I can do that?
Use moment.js library and code below:
Yup.object().shape({
busi_start_time: Yup.string().required("Start time cannot be empty"),
busi_end_time: Yup.string()
.required("end time cannot be empty")
.test("is-greater", "End time should be greater", function (value) {
const { busi_start_time} = this.parent;
return moment(value, "HH:mm").isSameOrAfter(moment(busi_start_time, "HH:mm"));
})
});
I have a task from my company where I have to show whether the username is taken or not, I am using formik and yup validation for the checks so for the time being I have added a custom test functionality to yup validation which shows whether the username is taken or not on the click of the submit button, however, my original task was to show the error message dynamically while the user enters the username, it should tell him if the the username is taken or not.
I understood that I might have to manipulate the default handleChange of formik, but I’m unable to do so.
Any help is highly appreciated!!!
validationSchema: Yup.object({
name: Yup.string()
.min(2, "Mininum 2 characters")
.max(30, "Maximum 30 characters")
.required("Your name is required"),
email: Yup.string()
.email("Invalid email format")
.test("email", "This email has already been registered", function (email) {
return checkAvailabilityEmail(email);
})
.required("Your email is required"),
username: Yup.string()
.min(1, "Mininum 1 characters")
.max(15, "Maximum 15 characters")
.test("username", "This username has already been taken", function (username) {
return checkAvailabilityUsername(username);
})
.required("You must enter a username"),
In your validation schema, just add the test function which is found in Yup. Yup also supports async/await as well!
Anyways, to answer your question, here's my example:
validationSchema: Yup.object({
email: Yup.string()
.min(8, 'Must be at least 8 characters')
.max(20, 'Must be less than 20 characters')
.required('Email is required')
.test('Unique Email', 'Email already in use', // <- key, message
function (value) {
return new Promise((resolve, reject) => {
axios.get(`http://localhost:8003/api/u/user/${value}/available`)
.then((res) => {
resolve(true)
})
.catch((error) => {
if (error.response.data.content === "The email has already been taken.") {
resolve(false);
}
})
})
}
),
}),
The value of the email is passed and called to the database which returns a response object. If the response object is an error and the error content is matched, it will be resolved to false and display the message, 'Email already in use'.
EDIT: If you do not want to validate on every keystroke, you can pass in some props, in particular, validateOnChange={false} or ValidateOnBlur={false}. This can help improve performance issues and reduce API calls to your backend!
<Formik
initialValues={{
firstName: '',
lastName: '',
email: '',
}}
validationSchema={validationSchema}
validateOnChange={false} // disable on every keystroke
...
>
To display your error messages accordingly:
{(errors.email && touched.email) && <span style={{ color: 'red', fontSize: '0.8rem', marginLeft: '1.5rem' }}>{errors.email}</span>}
I am trying to implement login functionality using Formik and Yup. This is my current schema
let loginSchema = yup.object().shape({loginId:
yup
.string()
.email("That doesn't look like a valid email")
.required("This field is required."),password: yup.string().required("This field is required."),});
But my loginId can either be a phone number or email. So, how do i add the validation based on the type of field that has been entered in the form. If its an email, trigger validation for email or if its phone number, i want to validate it against a regex.
Input field that accepts both email and phone:
const LoginSchema = yup.object().shape({
email_or_phone: yup.string()
.required('Email / Phone is required')
.test('email_or_phone', 'Email / Phone is invalid', (value) => {
return validateEmail(value) || validatePhone(parseInt(value ?? '0'));
}),
password: yup.string().required()
});
const validateEmail = (email: string | undefined) => {
return yup.string().email().isValidSync(email)
};
const validatePhone = (phone: number | undefined) => {
return yup.number().integer().positive().test(
(phone) => {
return (phone && phone.toString().length >= 8 && phone.toString().length <= 14) ? true : false;
}
).isValidSync(phone);
};
Solved email and PhoneNumber Validation
const loginValidationSchema = Yup.object({
email: Yup.string().when("isEmail", {
is: '1',
then: Yup.string()
.email("Please enter valid email")
.required("email cannot be empty"),
otherwise: Yup.string()
.required("phonenumber cannot be empty")
.min(6, 'phonenumber must be at least 6 char'),
}),
password: Yup.string()
.required("Password cannot be empty")
.min(6, 'Password must be at least 6 char'),
});
<Formik
validationSchema={loginValidationSchema}
initialValues={{ isEmail: 0, email: '', password: '' }}
onSubmit={}
>
{({ handleChange, handleBlur, handleSubmit, values, errors,
touched }) => (
<View>
<TextInput
placeholder="ramchandran2897#gmail.com"
onChangeText={(event)=>{
handleChange("email")(event)
if(Number(values.phonenumberOrEmail)){
handleChange("isEmail")('0')
}else{
handleChange("isEmail")('1')
}
}}
onBlur={handleBlur('email')}
value={values.email}
keyBoardType="email-address"
autoFocus={false}
returnKeyType='next'
returnKeyLabel='>'
onSubmitEditing={() => passwordRef.current?.focus()}
error={errors.email}
touched={touched.email}
/>
<TextInput
placeholder="****"
placeholderTextColor={Colors.darkLight}
onChangeText={handleChange('password')}
onBlur={handleBlur('password')}
value={values.password}
secureTextEntry={hidePassword}
isPassword={true}
hidePassword={hidePassword}
setHidePassword={setHidePassword}
min={6}
autoCapitalize='none'
keyboardAppearance='dark'
onSubmitEditing={handleSubmit}
ref={passwordRef}
error={errors.password}
touched={touched.password}
/>
<TextInput
onChangeText={handleChange('isEmail')}
keyBoardType='none'
/>
</View>
)}
</Formik>
If you want to dynamically validate your fields, use when for the validationSchema.
An example from the documentation.
let schema = object({
isBig: boolean(),
count: number()
.when('isBig', {
is: true, // alternatively: (val) => val == true
then: yup.number().min(5),
otherwise: yup.number().min(0),
})
.when('$other', (other, schema) => (other === 4 ? schema.max(6) : schema)),
});
So in your case you have to craft your is statement to decide whether it is an email of a phone number, then you can attach validation accordingly.
I didn't work with formik but face the same situation as you face here. I was working with Form Hook. Maybe somehow it will help you or someone.
First of all, add a hidden input after your main input in which the user will add phone or email. On change of that main input, you have to check that if this string contains '#' or not. If it contains # then make a state and update state with true like this.
const onChangeEmailOrPhone = (event) => {
let email = event.target.value.includes('#');
if (email) {
setIsEmail(true);
} else {
setIsEmail(false);
}
};
and set this state value to the hidden input just like this
<TextField
type="hidden"
name="isEmailValue"
inputRef={register}
value={isEmail}
/>
Following should be your validation schema to check weather isEmailValue is true or not, If true then you have to validate for email otherwise for the phone just like this.
let loginSchema = yup.object().shape({
emailOrPhone: yup.string().when('isEmailValue', {
is: 'true',
then: yup
.string()
.email('Please enter valid email')
.required('This field is required'),
otherwise: yup
.string()
.matches(phoneRegex, 'Please enter valid phone number')
.required('This field is required'),
})});
Following is phoneRegex for your help
const phoneRegex = /^(\+?\d{0,4})?\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{4}\)?)?$/;