Using Joi, require one of two fields to be non empty

后端 未结 3 1992
没有蜡笔的小新
没有蜡笔的小新 2021-01-07 21:28

If I have two fields, I\'d just like to validate when at least one field is a non empty string, but fail when both fields are empty strings.

Something like this does

3条回答
  •  没有蜡笔的小新
    2021-01-07 21:38

    An alternative way of using Joi.when() that worked for me:

    var schema = Joi.object().keys({
      a: Joi.string().allow(''),
      b: Joi.when('a', { is: '', then: Joi.string(), otherwise: Joi.string().allow('') })
    }).or('a', 'b')
    

    .or('a', 'b') prevents a AND b being null (as opposed to '').

提交回复
热议问题