Sencha Touch 2 Models – Custom Validation Functions

Occasionally, the built-in validations provided by the Ext.data.Validations singleton are not enough to satisfy your application’s requirements. Fortunately, it is possible to augment the Ext.data.Validations class with validation methods of our own.

For example, in the Room.js file we created in the previous Sencha Touch Model validations article of this series, you could add a roomRate validation like so:

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: 'inclusion', field: 'type', list: ['single', 'double', 'suite'], message: 'valid values are "single", "double" and "suite"' },
	    { type: 'roomRate', field: 'standardRate', message: 'must be between $100 and $1000 per night' }
        ]
    }
});

The roomRate is a type of validation that allows you to restrict a room’s rate to the $100 to $1000 per night range. In the index.html file, you will type the following code:

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

        Ext.applyIf(Ext.data.Validations, {
            roomRate: function (config, value) {
                // No configs read, so allow just value to be passed
                if (arguments.length === 1) {
                    value = config;
                }

                return value > 99 && value < 1001;
            }
        });

        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.length);

        // Each error has a field and a message property.
        errors.each(function (item, index, length) {
            console.log('Field "' + item.getField() + '" ' + item.getMessage());
        });
    }
});

If you run the application in Google Chrome and enable Chrome’s JavaScript console, you should see an output similar to this:

Sencha Touch Models Custom Validation

In Detail

It all starts with the model’s validations array, where you create an entry for the roomRate validation:

validations: [
	{ type: 'presence', field: 'floor' },
	{ type: 'roomRate', field: 'standardRate', message: 'must be between $100 and $1000 per night' },
	{ type: 'inclusion', field: 'type', list: ['single', 'double', 'suite'], message: 'valid values are "single", "double" and "suite"' }
]

This entry specifies the roomRate type, which does not exist in the Ext.data.Validations class, along with a value for the message property.

Then, you implement the new validation in the launch function of the application, using Ext.applyIf to add the roomRate method to the Ext.data.Validations class:

Ext.applyIf(Ext.data.Validations, {
	roomRate: function (config, value) {
		// If config was not passed, make value the config.
		if (arguments.length === 1) {
			value = config;
		}

		return value > 99 && value < 1001;
	}
});

As you can imagine, you can use this approach to create any type of validation logic needed by your application.

Want To Learn More?

My Sencha Touch books will teach you how to create a Sencha Touch application, step by step, from mockups to production build.

About Jorge

Jorge is the author of 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.
If you'd like to work with Jorge, contact him at ramonj[AT]miamicoder.com.

Comments

  1. can you write some example using model’s association? Can be very useful.

Speak Your Mind

*