最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Conditional field validation based on boolean prop - Stack Overflow

programmeradmin5浏览0评论

I want the favoriteAlcohol field to be validated/required only if props.isAdult passed to the ponent is true.

Yup.object().shape({
  favoriteAlcohol: Yup.string().when(props.isAdult, {
    is: true,
    then: Yup.string().required(),
  }),
  name: Yup.string().required('Nazwa jest wymagana'),
})

How can I do that?

Above solution does not work, because when takes form's "keys" as a first argument, and I passed prop.

One working solution would be to map prop.isAdult to isAdult form value field, and then I could pass 'isAdult' as a first argument to the when() function. Not the best solution, though.

I want the favoriteAlcohol field to be validated/required only if props.isAdult passed to the ponent is true.

Yup.object().shape({
  favoriteAlcohol: Yup.string().when(props.isAdult, {
    is: true,
    then: Yup.string().required(),
  }),
  name: Yup.string().required('Nazwa jest wymagana'),
})

How can I do that?

Above solution does not work, because when takes form's "keys" as a first argument, and I passed prop.

One working solution would be to map prop.isAdult to isAdult form value field, and then I could pass 'isAdult' as a first argument to the when() function. Not the best solution, though.

Share Improve this question asked Oct 26, 2020 at 12:57 wenoweno 86610 silver badges22 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8
const favoriteAlcohol = props.isAdult ? {favoriteAlcohol: Yup.string().required()} : {}

Yup.object().shape({
  ...favoriteAlcohol,
  name: Yup.string().required('Nazwa jest wymagana'),
})

If props.isAdult = true then, it will make

Yup.object().shape({
  favoriteAlcohol: Yup.string().required(),
  name: Yup.string().required('Nazwa jest wymagana'),
})

Otherwise, it will make

Yup.object().shape({
  name: Yup.string().required('Nazwa jest wymagana'),
})
发布评论

评论列表(0)

  1. 暂无评论