Yup : How to validate n input text fields only one is required

Viewed 37

I have React form and used yup validation. I have 5 input text fields from which at least one should be filled and accordingly show the error "Please fill at least one field". below is the code used.

Yup validation

initialValues={{
    domain0: "",
}}
validationSchema={(Yup) =>
    Yup.object().shape(Object.assign({
        domain0: Yup.string().required('Domain should not be blank'),
    }))}```

Form HTML

```<div>
<Label className="" text="Domains" />
<div className="oui-row oui-px-2">
    {[...Array(5)].map((e, i) => {
        return (
            <div className="col-4">
                <Input
                    type="text"
                    name={`domain${i}`}
                    value={values[`domain${i}`]}
                    validationProps={props}
                />
            </div>
        )
    })}
    </div>
</div>```

please suggest the best approach for the same and yup validation for the above condition
thanks in advance.
1 Answers
                Yup.object().shape(Object.assign({})).test('selectedOnce', 'Error', function (value) {
                    const { createError } = this;
                    if ((value.domain0 || value.domain1 || value.domain2 || value.domain3 || value.domain4)) {
                        return true;
                    } else {
                        return createError({ path: 'domainError', message: ""Select at least one field. });
                    }
                })}
<div className={errors.domainError !== undefined ? 'oui-mb-3' : ''} show={(props.touched.domain0 || props.touched.domain1 || props.touched.domain2 || props.touched.domain3 || props.touched.domain4) && errors.domainError !== undefined} > {errors.domainError}</div> ```


Above the one of the ways we can handle the validation of one of the field is required 



    
Related