Skip to content

Working with validations

Nikos Zinas edited this page May 17, 2014 · 1 revision

The core of the validation engine, is the Validator object. There you can define new validations functions, which you then can invoke in your models. Here is an example of the integer validation, which checks a property, if it's integer.

  integer : {
    test : function (value) {
      return /^\s*(\+|-)?\d+\s*$/.test(value);
    },
    error : function (property) {
      return 'Field "'+property+'" must be an integer.';
    }
  }

The key integer is the name of your validation. Each validation must have a test() function which will execute to test the validity and an error() function which will provide the default error message. The Validator object is meant to be edited by the developer, to add his own validations, which will be used in the models.

The defined validations that ship out of the box are:

  • required Test if a value is null
  • more Test if a value is larger than a threshold
  • less Test if a value is less than a threshold
  • integer Test if the value is an integer (based on format, "5" is still considered an integer)
  • number Test if the value is a number (based on format, "5.0" is still considered a number)
  • email Test if the value is a valid email format
  • expression Test against any regular expression

Using validations

Validations can be defined via the extend() method. Here is the example

Car.extend({
  validations : {
    brand : ['required'],
    cost : ['integer', {
      test : "more",
      params : [10000]
    }]
  }
});

The validations property, can have any column name as key. And for each column, you can define an array of validations that are defined in the validator. If you notice the example, you can see 2 ways for adding a validation to a column. Either as a string (like the required validation in the example, or as an object. The latter happens, when you need to pass more parameters in the validation function.

Also, you can add specific error messages for this Model. Lets change the message if the brand is not filled.

Car.extend({
  validations : {
    brand : ['required'],
    cost : ['integer', {
      test : "more",
      params : [10000]
    }]
  },
  messages : {
    required : function (property) {
      return "A car cannot be defined without a '"+property+"'";
    }
  }
});

Extending the Validator

Lets create a custom function, that checks if the car is newer than a specific year

Validator.newer = {
  test : function (value, year) {
    return value > year;
  },
  message : function (property, year) {
    return property + " should be later than "+year;
  }
}

// and you would use it like this

Car.extend({
  validations : {
    brand : ['required'],
    cost : ['integer', {
      test : "more",
      params : [10000]
    }],
    year : [{
      test : newer,
      params : [2010]
    }]
  }
});