How to implement backbone.js validations/custom validations?

2.3k Views Asked by At

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

2

There are 2 best solutions below

1
On

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';
        }
    }
});
0
On

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';
    }
  }
});