是的:如何验证n个输入文本字段只需要一个



我有React表单并使用了yup验证。我有5个输入文本字段,其中至少一个应该被填充;请至少填写一个字段";。下面是使用的代码。

Yup验证

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.
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 


相关内容

  • 没有找到相关文章

最新更新