Joi validation - dynamic control on 3 fields

Viewed 137

I'm dealing with 3 form fields in order to validate them. Here are the basic schema :

schema = {
    firstName: JoiExtend.string().allow(''),
    lastName: JoiExtend.string().allow(''),
    birthDate: JoiExtend
        .date().format("DD/MM/YYYY").utc()
        .allow(null).allow('')
  };

So the validation rules are :

  • If firstName is set with value, lastName must have a value
  • If lastName is set with value, firstName must have a value
  • If birthDate is set with value, firstName and lastName must have a value

I'm really struggling for doing this, I've started to work with this approach :

schema = {
    firstName: JoiExtend.when('lastName', {
      is: JoiExtend.string(),
      then: JoiExtend.string().required(),
      otherwise: JoiExtend.string().allow('')
    }),

    lastName: JoiExtend.when('firstName', {
      is: JoiExtend.string(),
      then: JoiExtend.string().required(),
      otherwise: JoiExtend.string().allow('')
    }),

    dateNaissance: JoiExtend
        .date().format("DD/MM/YYYY").utc()
        .label("La Date de naissance")
        .allow(null).allow('')
        .messages(this.getErrorMessage())
  };

But I have the following error : Uncaught Error: item added into group lastName created a dependencies error

Moreover, this code does not take into account the rule with birthDate

Any help ?

0 Answers
Related