Load, Validate, and Submit Forms using Ext JS 3.0: Part 2

Exclusive offer: get 50% off this eBook here
Ext JS 3.0 Cookbook

Ext JS 3.0 Cookbook — Save 50%

Clear step-by-step recipes for building impressive rich internet applications using the Ext JS JavaScript library

$29.99    $15.00
by Jorge Ramon | October 2009 | Cookbooks Open Source

Read Part One of Load, Validate, and Submit Forms using Ext JS 3.0.

Creating validation functions for URLs, email addresses, and other types of data

Ext JS has an extensive library of validation functions. This is how it can be used to validate URLs, email addresses, and other types of data.

The following screenshot shows email address validation in action:

Load, Validate, and Submit Forms using Ext JS 3.0: Part 2

This screenshot displays URL validation in action:

Load, Validate, and Submit Forms using Ext JS 3.0: Part 2

How to do it...

  1. Initialize the QuickTips singleton:
    Ext.QuickTips.init();
  2. Create a form with fields that accept specific data formats:
    Ext.onReady(function() {
    var commentForm = new Ext.FormPanel({
    frame: true,
    title: 'Send your comments',
    bodyStyle: 'padding:5px',
    width: 550,
    layout: 'form',
    defaults: { msgTarget: 'side' },
    items: [
    { xtype: 'textfield',
    fieldLabel: 'Name',
    name: 'name',
    anchor: '95%',
    allowBlank: false
    },
    {
    xtype: 'textfield',
    fieldLabel: 'Email',
    name: 'email',
    anchor: '95%',
    vtype: 'email'
    },
    {
    xtype: 'textfield',
    fieldLabel: 'Web page',
    name: 'webPage',
    vtype: 'url',
    anchor: '95%'
    },
    {
    xtype: 'textarea',
    fieldLabel: 'Comments',
    name: 'comments',
    anchor: '95%',
    height: 150,
    allowBlank: false
    }],
    buttons: [{
    text: 'Send'
    },
    {
    text: 'Cancel'
    }]
    });
    commentForm.render(document.body);
    });

How it works...

The vtype configuration option specifies which validation function will be applied to the field.

There's more...

Validation types in Ext JS include alphanumeric, numeric, URL, and email formats. You can extend this feature with custom validation functions, and virtually, any format can be validated. For example, the following code shows how you can add a validation type for JPG and PNG files:

Ext.apply(Ext.form.VTypes, {
Picture: function(v) {
return /^.*.(jpg|JPG|png|PNG)$/.test(v);
},
PictureText: 'Must be a JPG or PNG file';
});

If you need to replace the default error text provided by the validation type, you can do so by using the vtypeText configuration option:

{
xtype: 'textfield',
fieldLabel: 'Web page',
name: 'webPage',
vtype: 'url',
vtypeText: 'I am afraid that you did not enter a URL',
anchor: '95%'
}

See also...

  • The Specifying the required fields in a form recipe, covered earlier in this article, explains how to make some form fields required
  • The Setting the minimum and maximum length allowed for a field's value recipe, covered earlier in this article, explains how to restrict the number of characters entered in a field
  • The Changing the location where validation errors are displayed recipe, covered earlier in this article, shows how to relocate a field's error icon
  • Refer to the previous recipe, Deferring field validation until form submission, to know how to validate all fields at once upon form submission, instead of using the default automatic field validation
  • The next recipe, Confirming passwords and validating dates using relational field validation, explains how to perform validation when the value of one field depends on the value of another field
  • The Rounding up your validation strategy with server-side validation of form fields recipe (covered later in this article) explains how to perform server-side validation

Confirming passwords and validating dates using relational field validation

Frequently, you face scenarios where the values of two fields need to match, or the value of one field depends on the value of another field.

Let's examine how to build a registration form that requires the user to confirm his or her password when signing up.

Load, Validate, and Submit Forms using Ext JS 3.0: Part 2

How to do it…

  1. Initialize the QuickTips singleton:
    Ext.QuickTips.init();
  2. Create a custom vtype to handle the relational validation of the password:
    Ext.apply(Ext.form.VTypes, {
    password: function(val, field) {
    if (field.initialPassField) {
    var pwd = Ext.getCmp(field.initialPassField);
    return (val == pwd.getValue());
    }
    return true;
    },
    passwordText: 'What are you doing?<br/>The passwords entered
    do not match!'
    });

  3. Create the signup form:
    var signupForm = { xtype: 'form',
    id: 'register-form',
    labelWidth: 125,
    bodyStyle: 'padding:15px;background:transparent',
    border: false,
    url: 'signup.php',
    items: [
    { xtype: 'box',
    autoEl: { tag: 'div',
    html: '<div class="app-msg"><img src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="img/businessman
    add.png" class="app-img" />
    Register for The Magic Forum</div>'
    }
    },
    { xtype: 'textfield', id: 'email', fieldLabel: 'Email',
    allowBlank: false, minLength: 3,
    maxLength: 64,anchor:'90%', vtype:'email'
    },
    { xtype: 'textfield', id: 'pwd', fieldLabel: 'Password',
    inputType: 'password',allowBlank: false, minLength: 6,
    maxLength: 32,anchor:'90%',
    minLengthText: 'Password must be at least 6 characters
    long.'
    },
    { xtype: 'textfield', id: 'pwd-confirm',
    fieldLabel: 'Confirm Password', inputType: 'password',
    allowBlank: false, minLength: 6,
    maxLength: 32,anchor:'90%',
    minLengthText: 'Password must be at least 6 characters
    long.',
    vtype: 'password', initialPassField: 'pwd'
    }
    ],
    buttons: [{
    text: 'Register',
    handler: function() {
    Ext.getCmp('register-form').getForm().submit();
    }
    },
    {
    text: 'Cancel',
    handler: function() {
    win.hide();
    }
    }]
    }

  4. Create the window that will host the signup form:
    Ext.onReady(function() {
    win = new Ext.Window({
    layout: 'form',
    width: 340,
    autoHeight: true,
    closeAction: 'hide',
    items: [signupForm]
    });
    win.show();
Ext JS 3.0 Cookbook Clear step-by-step recipes for building impressive rich internet applications using the Ext JS JavaScript library
Published: October 2009
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

How it works

The first step is to initialize the QuickTips singleton. This allows the form's validation errors to show as tool tips.

Next, a custom vtype is created to support the relational validation of the password. A vtype consists of a validation function and the text to use when there is a validation error. The password validation function compares the values of the two password fields:

password: function(val, field) {
if (field.initialPassField) {
var pwd = Ext.getCmp(field.initialPassField);
return (val == pwd.getValue());
}
return true;
}

When the validation fails, the error text is used:

passwordText: 'What are you doing?<br/>The passwords entered do
not match!'

What follows is the creation and display of the signup form. Notice how the second password field has references to the custom vtype and the first password field. This allows the validation function in the custom vtype to work:

{ xtype: 'textfield', id: 'pwd-confirm',
fieldLabel: 'Confirm Password', inputType: 'password',
allowBlank: false, minLength: 6, maxLength: 32,anchor:'90%',
minLengthText: 'Password must be at least 6 characters long.',
vtype: 'password', initialPassField: 'pwd'
}

There's more...

You can also use this technique for validating date fields that act as a date range, where selecting an initial date in one field sets the minimum or maximum value for the other field.

Load, Validate, and Submit Forms using Ext JS 3.0: Part 2

See also…

  • The Specifying the required fields in a form recipe, covered earlier in this article, explains how to make some form fields required
  • The Setting the minimum and maximum length allowed for a field's value recipe (covered earlier in this article) explains how to restrict the number of characters entered in a field
  • The Changing the location where validation errors are displayed recipe, covered earlier in this article, shows how to relocate a field's error icon
  • Refer to the Deferring field validation until form submission recipe, covered earlier in this article, to know how to validate all fields at once upon form submission, instead of using the default automatic field validation
  • Refer to the previous recipe, Creating validation functions for URLs, email addresses, and other types of data, for an explanation of the validation functions available in Ext JS
  • The following recipe, Rounding up your validation strategy with server-side validation of form fields, explains how to perform server-side validation

 

Rounding up your validation strategy with server-side validation of form fields

Server-side validation should be an important component of your validation strategy for any application. This recipe explains how to send validation codes and messages to a login form from the server-side code.

The login form built in this recipe performs client-side validation. Upon submission, the server returns an error code and a message, as shown in the next screenshot:

Load, Validate, and Submit Forms using Ext JS 3.0: Part 2

How to do it...

  1. Initialize the QuickTips singleton so that we can have error messages as tool tips:
    Ext.QuickTips.init();
  2. Define the login form:
    var loginForm = { xtype: 'form',
    id: 'login-form',
    bodyStyle: 'padding:15px;background:transparent',
    border: false,
    url:'login.php',
    items: [
    { xtype: 'box', autoEl: { tag: 'div',
    html: '<div class="app-msg">
    <img src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="img/magic-wand.png" class="app-img" />
    Log in to The Magic Forum</div>'
    }
    },
    { xtype: 'textfield', id: 'login-user',
    fieldLabel: 'Username', allowBlank: false,
    minLength: 3, maxLength: 32
    },
    { xtype: 'textfield', id: 'login-pwd',
    fieldLabel: 'Password', inputType: 'password',
    allowBlank: false, minLength: 6,
    maxLength: 32, minLengthText: 'Password must be at least
    6 characters long.'
    }
    ],
    buttons: [{
    text: 'Login',
    handler: function() {
    Ext.getCmp('login-form').getForm().
    submit({waitMsg: 'Please wait...' });
    }
    },
    {
    text: 'Cancel',
    handler: function() {
    win.hide();
    }
    }]
    }
  3. Create the window that will host the login form:
    Ext.onReady(function() {
    win = new Ext.Window({
    layout: 'form',
    width: 340,
    autoHeight: true,
    closeAction: 'hide',
    items: [loginForm]
    });
    win.show();

  4. Create the login.php server page:
    <?php
    echo "{success:false,errors:[{id:'login-pwd',msg:'Sorry, you have
    to type the magic word!'}]}";
    ?>

How it works...

The first step is to initialize the QuickTips singleton, so that we can show the form's validation errors as tool tips.

Next, the form and the window that serves as a host for the form are built. The form is set up to perform client-side validation as explained in the previous recipes in this article.

The interesting part of this recipe is the server page that handles the form submission. The PHP code here illustrates which elements are necessary to notify the form that one or more fields are invalid:

echo "{success:false,errors:[{id:'login-pwd',msg:'Sorry, you have to
type the magic word!'}]}";

The server page returns the JSON representation of an object with two properties—success and errors. The success property is present both when there are problems with the validation (success = false), or when the submission was successful (success = true). Errors is an array containing one object for each invalid field. This object in turn contains the ID of the invalid field and the error message:

{id:'login-pwd',msg:'Sorry, you have to type the magic word!'}

There's more...

A comprehensive validation strategy is always recommended. Even though the client-side validation facilities in Ext JS are very powerful, do not skip server-side validation. Use it to add robustness and resiliency to your applications.

See also...

  • The Specifying required fields in a form recipe, covered earlier in this article, explains how to make some form fields required
  • Refer to the Deferring field validation until form submission recipe, covered earlier in this article, to know how to validate all fields at once upon form submission, instead of using the default automatic field validation

>> Continue Reading Load, Validate, and Submit Forms using Ext JS 3.0: Part 3

 

[ 1 | 2 | 3 ]

 

If you have read this article you may be interested to view :

 

Ext JS 3.0 Cookbook Clear step-by-step recipes for building impressive rich internet applications using the Ext JS JavaScript library
Published: October 2009
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

About the Author :


Jorge Ramon is the Vice President of Development for Taladro Systems LLC, where he has led the design and development of a number of software products for the law industry—including QwikTime™ and LawDrill™.

Jorge has over 16 years of experience as a software developer and has also worked creating web applications, search engines, and automatic-control software. He actively contributes to the software development community through his blog: MiamiCoder.com.

Books From Packt

Moodle 1.9 for Second Language Teaching
Moodle 1.9 for Second Language Teaching

eZ Publish 4: Enterprise Web Sites Step-by-Step
eZ Publish 4: Enterprise Web Sites Step-by-Step

Joomla! 1.5 Development Cookbook
Joomla! 1.5 Development Cookbook

Joomla! 1.5 SEO
Joomla! 1.5 SEO

WordPress 2.7 Cookbook
WordPress 2.7 Cookbook

Pentaho Reporting 3.5 for Java Developers
Pentaho Reporting 3.5 for Java Developers

SOA Cookbook
SOA Cookbook

Hacking Vim: A Cookbook to get the Most out of the Latest Vim Editor
Hacking Vim: A Cookbook to get the Most out of the Latest Vim Editor

 

No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
f
e
j
g
s
y
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software