Tuesday, 12 March 2013

How to Use Model Validation in Sencha Touch 2

In Sencha Touch 2, Models have strong support for validating its data. In Modal, Validation Configuration follows the same format as the Field Configuration. It expects the field name and type of validation. Following are the validation types available (as per Sencha documentation)

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.

To demonstrate this, we're going to build up a User Model with some Validations

Ext.define('App.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: 'length',
               field: 'Name',
                min: 6
            }
       ]
    }
});

Both Name and Age Fields are required and can't be empty. Name Field must have Min 6 characters. Lets create a User and validate it using validate().

Example 1:

var usr = Ext.create('App.model.User',{
     Name: 'Ravi'
});

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

if (!errs.isValid()) {
   errs.each(function (err) {
   msg += err.getField() + ' : ' + err.getMessage() + '<br/>';
   });
   Ext.Msg.alert('ERROR', msg);

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

Output: ERROR Alert Message - "Age : must be present && Name : is the wrong length".

Example 2:

var usr = Ext.create('App.model.User',{
     Name: 'A Suresh',
     Age: 26
});

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

if (!errs.isValid()) {
    errs.each(function (err) {
    msg += err.getField() + ' : ' + err.getMessage() + '<br/>';
    });
    Ext.Msg.alert('ERROR', msg);
} else {
   Ext.Msg.alert('SUCCESS', 'Looks like the model is valid');
}
Output: SUCCESS Alert Message - "Looks like the model is valid".

Hope, you enjoyed this Post.

No comments:

Post a Comment