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

后端 未结 3 1974
没有蜡笔的小新
没有蜡笔的小新 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 '').

    0 讨论(0)
  • 2021-01-07 21:41

    If you want to express the dependency between 2 fields without having to repeat all other parts of the object, you could use when:

    var schema = Joi.object().keys({
      a: Joi.string().allow(''),
      b: Joi.string().allow('').when('a', { is: '', then: Joi.string() })
    }).or('a', 'b');
    
    0 讨论(0)
  • 2021-01-07 21:49

    Code below worked for me. I used alternatives because .or is really testing for the existence of keys and what you really wanted was an alternative where you would allow one key or the other to be empty.

    var console = require("consoleit");
    var Joi = require('joi');
    
    var schema = Joi.alternatives().try(
      Joi.object().keys({
        a: Joi.string().allow(''),
        b: Joi.string()
        }),
      Joi.object().keys({
        a: Joi.string(),
        b: Joi.string().allow('')
        })
    );
    
    var tests = [
      // both empty - should fail
      {a: '', b: ''},
      // one not empty - should pass but is FAILING
      {a: 'aa', b: ''},
      // both not empty - should pass
      {a: 'aa', b: 'bb'},
      // one not empty, other key missing - should pass
      {a: 'aa'}
    ];
    
    for(var i = 0; i < tests.length; i++) {
      console.log(i, Joi.validate(tests[i], schema)['error']);
    }
    
    0 讨论(0)
提交回复
热议问题