0

Need to validate one field based on the value of other field using backbone validation js. How to approach this ? Is it possible to validate using lib methods like range validator, max validator OR should I go with custom method ??

Normally this is how it looks,

bindings: {

    'value1': {

        Observe: 'value1',

        Setoptions:{

            Validate:true

        }

    }
}

This will call validate method

Validation: {

    Value1: {

        Pattern: number,

        Min: 0
        /* here we need to validate value1 < value2 where value 2 is value of another input field */

    }
}

Thanks

Mohamed Shaaban
  • 1,129
  • 6
  • 13
user2526641
  • 319
  • 1
  • 4
  • 19

2 Answers2

0

I don't see any thing that would fit to compare two values, see in built-in-validatiors

You can use custom validator if the usage is repetitive. Here using validator method

Backbone.Model.extend({
    validation: {
      value1: function(value, attr, computedState) {
          if(value < computedState.value2) {
            return 'Error message';
          }
      }
    }
});

You can use named method validator as well

Backbone.Model.extend({
    validation: {
      value1: {
          min: 0,
          pattern: 'number',
          fn: 'greaterThan'
      }
    },
    greaterThan: function(value, attr, computedState) {
        if(value < computedState.value2) {
          return 'Error message';
        }
    }
});
Sami
  • 3,926
  • 1
  • 29
  • 42
  • I used named method validators that worked thanks... Source : http://thedersen.com/projects/backbone-validation/ – user2526641 Jun 23 '15 at 12:44
0

You can use https://github.com/thedersen/backbone.validation And use one of 2 case:

https://github.com/thedersen/backbone.validation#do-you-support-conditional-validation

validation: {
  attribute: {
    required: function(val, attr, computed) {
      return computed.someOtherAttribute === 'foo';
    },
    length: 10
  }
}

or

https://github.com/thedersen/backbone.validation#can-i-call-one-of-the-built-in-validators-from-a-custom-validator

_.extend(Backbone.Validation.validators, {
  custom: function(value, attr, customValue, model) {
    return this.length(value, attr, 4, model) || this.custom2(value, attr, customValue, model);
  },
  custom2: function(value, attr, customValue, model) {
    if (value !== customValue) {
      return 'error';
    }
  }
});