Jorge is the author of three software development books: "Building a Sencha Touch Application", "How to Build a jQuery Mobile Application", and the "Ext JS 3.0 Cookbook". He runs a software development and developer education shop that focuses on mobile, web and desktop technologies. Jorge is a DZone MVB and is not an employee of DZone and has posted 45 posts at DZone. You can read more from them at their website. View Full User Profile

Sencha Touch 2 Models – Model Validations

07.13.2012
| 2690 views |
  • submit to reddit

In this article we are going to explore Sencha Touch model validations.

Validations are a set of functions that can be used to validate the values of a model’s fields. Their functionality is encapsulated in the Validations class, which is a singleton.

You set up model validations through the model’s validations config. Sencha Touch defines built-in validations of the following types:

  • email, which validates that a field’s value is in the format of an email address:
    validations: [{ type: 'email', field: 'emailAddress'}]
  • exclusion, which validates that a field’s value is not present in a predefined list of values:
    validations: [{ type: 'exclusion', field: 'username', list: ['Administrator', 'PowerUser', 'Guest', 'Everyone']}]
    
  • inclusion, which validates that a field’s value is present in a predefined list of values:
    validations: [{ type: 'inclusion', field: 'size', list: ['Large', 'Medium', 'Small']}]
    
  • format, which validates that a field’s value conforms to a format defined by a configured regular expression:
    validations: [{ type: 'format', field: 'username', matcher: /([a-z]+)[0-9]{2,3}/}]
    
  • length, which validates that the length a field’s value is between the configured minimum and maximum values:
    validations: [{ type: 'length', field: 'password', min: 7, max: 16}]
    
  • presence, which validates that a given field is assigned a value:
    validations: [{ type: 'presence', field: 'firstName'}]

 

After setting up validations, you use them by invoking the validate function on the model. Let’s see an example.

Validating a Model

First, let’s set up a sample application with a set of directories like this:

Our index.html file must contain references to the framework’s files in its head section:

<link href="../../../lib/st2/resources/css/sencha-touch.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../../../lib/st2/sencha-touch-debug.js"></script>
<script type="text/javascript">
        // Application goes here.
</script>

In the Room.js file, let’s define the Room model as follows:

Ext.define('App.model.Room', {
    extend: 'Ext.data.Model',
    config: {
        fields: [
            { name: 'id', type: 'int' },
            { name: 'floor', type: 'string' },
            { name: 'type', type: 'string' },
            { name: 'standardRate', type: 'float' },
            { name: 'smoking', type: 'string' },
            { name: 'status', type: 'int' }
        ],
        validations: [
            { type: 'presence', field: 'floor' },
            { type: 'length', field: 'standardRate', min: 2 },
            { type: 'inclusion', field: 'type', list: ['single', 'double', 'suite'] }
        ]
    }
});

Note the validations config, where we defined validations of types presence, length and inclusion.

Let’s switch over to the index.html file and validate a model instance:

Ext.application({
    name: 'App',
    models: ['Room'],
    launch: function () {

        var myRoom = Ext.create('App.model.Room', {
            id: 1,
            standardRate: 5,
            type: 'Royal Suite',
            status: 1
        });

        // Validating a model.
        var errors = myRoom.validate();

        // Errors is a collection
        console.log('Number of errors: ' + errors.getCount());

        errors.each(function (item, index, length) {
            // Each item in the errors collection is an instance of the Ext.data.Error class.
            console.log('Field "' + item.getField() + '" ' + item.getMessage());
        });
    }
});

If we open the index.html in a WebKit browser and examine the JavaScript console, we will see an output like this:

In Detail

The first detail we need to look at is how we define model validations, something we did in the Room.js file:

Ext.define('App.model.Room', {
    extend: 'Ext.data.Model',
    config: {
        fields: [
            { name: 'id', type: 'int' },
            { name: 'floor', type: 'string' },
            { name: 'type', type: 'string' },
            { name: 'standardRate', type: 'float' },
            { name: 'smoking', type: 'string' },
            { name: 'status', type: 'int' }
        ],
        validations: [
            { type: 'presence', field: 'floor' },
            { type: 'length', field: 'standardRate', min: 2 },
            { type: 'inclusion', field: 'type', list: ['single', 'double', 'suite'] }
        ]
    }
});

These validations mean that the floor field is required, the value of the standardRate field must have at least two characters, and the value of the type field must be ‘single’, ‘double’ or ‘suite’.

In the application, we first create an instance of the model:

var myRoom = Ext.create('App.model.Room', {
    id: 1,
    standardRate: 5,
    type: 'Royal Suite',
    status: 1
});

Then, we invoke the validation function:

// Validating a model.
var errors = myRoom.validate();

The validate method returns an instance of the Ext.data.Errors class. This utility class contains a collection of objects representing each of the validation errors that occurred. It also contains helper functions that allow you to retrieve information about each error, such as the field that caused the error condition and the error message.

This is how you can use the Errors object:

// Errors is a collection
console.log('Number of errors: ' + errors.getCount());

errors.each(function (item, index, length) {
    // Each item in the errors collection is an instance of the Ext.data.Error class.
    console.log('Field "' + item.getField() + '" ' + item.getMessage());
});

Note how each error has a getField and getMessage function. These are the methods you can use to determine what field caused the error condition and what is the error message.

You can also use the getByField function of the errors object, which itself returns an array with the errors for the given field:

errors.getByField('floor');  // returns [{field: 'floor',  message: 'Field "floor" must be present'}]

What’s Next

In the next article of this series we will continue our tour of Sencha Touch 2 models. Stay tuned!

 

 

 

 

 

 

 

 

Published at DZone with permission of Jorge Ramon, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)