Sunday 31 March 2013

Create a Custom Model Validation Method in Sencha Touch 2

If you don't have knowledge on Model Validation in Sencha Touch 2 , Please visit this link for brief introduction about how model validation works in sencha touch2.

 Sencha Touch 2 Models have strong support for validating its data and it supports various validation types shown below

 1) presence -  Ensures that the field has a value. Zero counts as a valid value but empty strings do not.

 2) length  - Ensures that a string is between a minimum and maximum length. Both constraints are optional.

 3) format - Ensures that a string matches a regular expression format. In the example above we ensure that the age field is four numbers followed by at least one letter.

 4) inclusion - Ensures that a value is within a specific set of values (for example, ensuring gender is either male or female).

 5) exclusion - Ensures that a value is not one of the specific set of values (for example, blacklisting usernames like 'admin').

6) email - Ensures that the filed value matches with the format of an email address.

 In addition to it, Sencha Touch 2 also supports for creating custom Model validation.

 Let's see an example which validates user age is greater than 18 years. First create a User Model Class with Fields Name, Age

 Ext.define('MyApp.model.User',{
     extend: 'Ext.data.Model',
     alias: 'model.User',
       config: {
           fields: [
           {
              name: 'Name'

           },
           {
              name: 'Age'
            }
           ],
           validations: [
           {
              type: 'presence',
              field: 'Name'
           },
           {

              type: 'presence',
              field: 'Age'

           },
           {
              type: 'checkAge',
              field: 'Age',
              message: 'You must be greater than 18 years of Age.'

           }]
     }

});

 We have added 'checkAge' as the custom validation type for field 'Age' and provided an error message when validation fails. Now let's see the implementation

 Ext.applyIf(Ext.data.Validations, {

    checkAge: function (config, value) {

        if (arguments.length === 1) {
             value = config;
        }
           return value >= 18;
        }
 });

 Ext.applyIf() is used to Copy all the config properties to object if they don't already exist.  So by using  this function we are copying 'checkAge' config properties to the 'Ext.data.Validations' class. Ext.data.Validations is a singleton class that contains a set of validation functions that can be used to validate any type of data. This class is mostly used for model validations, where they are automatically set up and executed.

 Now, Let's create an instance for already defined User Model Class using Ext.create() by setting fields with values and apply validation using validate(). This method returns error objects. Using isValid() method, we can check whether is there any errors. if error exists, we are forming error message using Ext.each() else we are display success message.

 var usr = Ext.create('MyApp.model.User',{

     Name: 'Ravi',
     Age: 5
 });

 var errs = usr.validate();
 var msg = '';

 if (!errs.isValid()) {

   errs.each(function (err) {

   msg += err.getField() + ' : ' + err.getMessage() + '';

   });

   Ext.Msg.alert('ERROR', msg);

 } else {

   Ext.Msg.alert('SUCCESS', 'Looks like the model is valid');

 }

 Output: ERROR Alert Message - "Age : You must be greater than 18 years of Age".

Important Note: You need to include Ext.data.Validations class as the requires class  in the Ext.application.

 I hope, you enjoyed this Post.

No comments:

Post a Comment