Conditional validation with Yup and Formik
You can conditionally add to your validation schema just like any other object:
let validationShape = {
company: Yup.object().shape({
name: Yup.string().required('Field is required'),
address: Yup.string().required('Field is required'),
email: Yup.string()
.email('Wrong e-mail format')
.required('Field is required')
})
};
if (this.state.isPerson) {
validationShape.person = Yup.object().shape({
name: Yup.string().required('Field is required'),
surname: Yup.string().required('Field is required'),
middleName: Yup.string().required('Field is required'),
email: Yup.string()
.email('Wrong e-mail format')
.required('Field is required');
}
const validationSchema = Yup.object().shape(validationShape);
Yup conditional validation depending on if another field is valid?
I figured it out. I have divided the main schema into an emailSchema and a nameSchema, and then I used the concat method based on the step of the registration (1 being the step with the frist name field).
const schema = step === 1 ? emailSchema.concat(nameSchema) : emailSchema
conditional validation with yup
The construct:
.when("out", {
is: !disableOutCounterField,
compares the out
value with !disableOutCounterField
, and if they are equal, the then
rule is applied. But quite likely they are never the same.
The check that is needed here is just the value of !disableOutCounterField
by itself, for any value of out
. This can be done using an expression:
.when("out", {
is: value => !disableOutCounterField,
In words: for every out
value, return !disableOutCounterField
, and if it returns true, apply the then
part.
Formik and Yup conditional validation not working with useState
Changing the Switch
value does not affect Formik's hasSpouse
value.
Refactor code as below
<Switch
onValueChange={(value) => {
props.setFieldValue("hasSpouse", value);
}}
value={props.values.hasSpouse}
/>;
Related Topics
How to Add Spaces to for Loop Output in JavaScript
Set Focus to the Next Input Element
Angular:Onclick on HTML Element According to Its Class
How to Tell If a Dom Element Is Visible in the Current Viewport
How to Execute a JavaScript Function from the Java Part of Jsp
Convert an Object With Multiple Values Per Key into Array of Objects in Js
Display Data Label (Legend) in Line-Chart Using Chartjs
Get Weeks in Month Through JavaScript
How to Set Profile Image as First Letters of First and Last Name
Remove Specific Characters from String Jquery
How to Send a Http Delete Request from Browser
Why Does Prettier Not Format Code in VS Code
How to Implement Multiple Checkbox Using React Hook
How to Remove Image from Browser Cache
Recursively Find Keys on an Object
Javascript Onclick Increment Number