eivindfjeldstad/validate

Allow dependencies between fields

Closed this issue · 4 comments

It would be great allowing dependencies between two or more fields. For example, if I have this user:

const user = new Schema({
  username: {
    type: String,
    required: true,
    length: { min: 3, max: 32 }
  },
  email: {
    type: String
  },
  phoneNumber: {
    type: String
  }
})

Validate that this user has registered its email or its phone number. That is, if the email is provided, I don't need (or I don't want) the phone number, and viceversa. Use cases:

  • Require both fields (already implemented)
  • Require just one field: if email is provided, fail when phoneNumber (or other dependencies) is provided. Fail when no dependencies are provided.
  • Require at least one field: if email is provided, don't fail when phoneNumber (or other dependencies) is provided. Fail when no dependencies are provided.

Many thanks :)

Thanks for the suggestion! My goal has been to keep this library as lightweight as possible, while providing hooks for people to implement their own stuff. There's probably something we could do to make it easier, but in the meantime you could do this with a custom validator

const maybeRequired = (val, ctx) => val != null || ctx.phoneNumber != null;

const user = new Schema({
  email: {
    type: String,
    use: { maybeRequired }
  },
  phoneNumber: {
    type: String
  }
});

Yes, I tried something like that, but it doesn't really work since validate/property.js is validating the required type in the first place: if there's no required validation and no value, it stops validating the following validations, so it never reaches the maybeRequired one.

Ah sorry, of course you're right. That's actually a very persuasive argument for fixing #65

Should be fixed with commit d1c78c9