Skip to content

Conditional Validator

Asaf Shakarchi edited this page · 1 revision
Clone this wiki locally

Each validator may contain an if / unless property in its options hash.

The value of the if/unless properties can be either one of the following:

  • An inline function (see example below)
  • a string that represents a property on the object,
  • a string that represents a function on the object.

The result of the function execution must be boolean.

Example

a User model may have a password attribute, which may have some length validator attached to ensure that the password length is at least 6 chars.

But passwords are only required if the user is authenticated locally (assuming the app supports external authentication providers such as facebook or google)

So, assuming we have another property on the user named provider, we only want to validate the password field if provider attribute equals LOCAL.

User = model("User").attr('provider').attr('password', {
  validations: {
    length: {
      minimum: 6,
      if: function(model, validator) {
        //length validator should be executed only if 'provider' attribute is LOCAL
        model.provider() === 'LOCAL'
      }
    }
  }
});

u1 = User.create();
u1.provider('LOCAL')
u1.password('weak');

//length validator WILL be executed because provider is 'LOCAL'
p1.validate().then(function() {
  console.log(p1.isValid);
  //prints false
});


u1.provider('FACEBOOK')
u1.password(null)

//length validator WONT be executed because provider is 'LOCAL'
p1.validate().then(function() {
  console.log(p1.isValid);
  //prints true
});

This of course works for any other validators.

Something went wrong with that request. Please try again.