Thursday 4 July 2013

Add Validation to form fields blur event in Sencha Touch

As requested by one of my reader, Today we are going to see how to add validation to form fields using blur event in Sencha Touch 2. For demonstration, we will be creating a form panel with two fields Username and Password and attach blur event to the two fields using the listeners configuration in order to do validation. Let's see the implementation
Ext.define('MyApp.view.FormPanel', {
    extend: 'Ext.form.Panel',
    alias: 'widget.FormPanel',

    config: {
        items: [{
            xtype: 'textfield',
            itemId: 'username',
            label: 'Username',
            placeHolder: 'Enter Username'
        }, {
            xtype: 'passwordfield',
            itemId: 'password',
            label: 'Password',
            placeHolder: 'Enter Password'
        }],

        listeners: [{
            fn: 'onUsernamefieldBlur',
            event: 'blur',
            delegate: '#username'
        }, {
            fn: 'onPasswordfieldBlur',
            event: 'blur',
            delegate: '#password'
        }]
    },

    onUsernamefieldBlur: function (textfield, e, eOpts) {

        if (textfield.getValue() === '') {
            Ext.Msg.alert("Username can't be empty");
            textfield.setFocus(true);
        }
    },

    onPasswordfieldBlur: function (textfield, e, eOpts) {

        if (textfield.getValue() === '') {
            Ext.Msg.alert("Password can't be empty");
            textfield.setFocus(true);
        }
    }
});

Explanation:

In Form Panel Class, we are going to create two fields username, password with itemId confguration value set as the field names. Then, we are going to attach blur() event listeners  to the two fields using listeners configuration, delegate property referring to field itemId configuration and function names that will triggered when the blur event fires.

Inside function definition, I just added an empty check for the two fields. You can expand this by adding length, alphanumeric characters and other special characters validations. I will leave this implementation to the readers.

Following is the output, when i run the code in the Google Chrome



Hope, you enjoyed this Post.

1 comment:

  1. If i add emailfield in the above example, and do validation in listener.
    How can i validate email in listeners.

    ReplyDelete