Vous êtes sur la page 1sur 3

ExtJs 4 validate HTML form fields using

vtype
It's a good practice to validate the form fields for basic stuff such as required fields before you making
Ajax request by using the method isValid(), basically to keep load off the sever for trivial validations.
Before you can use the isValid() method the field must be specify the validation rules otherwise it will not
throw any errors.


You may be well aware of basic validation such as whether the field is requried or not using the
allowBlank property. By default the allowBlank property is set to true meaning that the textfield can be
left blank. If you set the property to false it will make sure that the field is required. Here is an example
defaults: {
anchor: '100%',
allowBlank: false,
msgTarget: 'side',
labelWidth: 75
},

items: [{
xtype: 'textfield',
name: 'filename',
fieldLabel: 'File Name'
}
..........
..........




Now to do other types of validations such as making sure input text value is alphanumeric ExtJs provides
validation type (Ext.form.field.VTypes) object. It contains the following field validation functions right
out of the box
alpha
alphanum
email
url

Here is how to validate a URL using vtype
{
xtype: 'textfield',
name: 'myURL',
fieldLabel: 'Website',
vtype: 'url'
}

Tip: I f you need to replace the default error message provided by validation type use the VtypeText
configuration option.


ExtJs Custom Validation Types

Now how to do validations not provided by the ExtJs library. You can create custom vtypes and use them
in
your form fields. Here we have created a custom vtype that makes sure the file is a Microsoft Excel by
checking the file extension for xls or xlsx. The example below takes the input value and checks it against
a Regular Expression and returns true or false. You can use any logic in that function based on your
requirement and return true or false to validate the field. It can be used to validate date ranges, making
sure the field data is valid based on some other field that is on the form, etc.
Ext.apply(Ext.form.field.VTypes, {

// vtype validation function
file : function(val, field) {
var fileName = /^.*\.(xlsx|xls)$/i;
return fileName.test(val);
},
// vtype Text property to display error Text
// when the validation function returns false
fileText : "File must be Microsoft Excel",
// vtype Mask property for keystroke filter mask
fileMask : /[a-z_\.]/i

});

{
xtype: 'filefield',
id: 'myFile',
emptyText: 'Select a File to Upload',
fieldLabel: 'Select a File',
name: 'fileSelected',
vtype: 'file',
buttonText: '',
buttonConfig: {
iconCls: 'upload-icon'
}
}




Here is another example of custom vtype provided in the Sencha docs to validate an IP Address
// custom Vtype for vtype:'IPAddress'
Ext.apply(Ext.form.field.VTypes, {
IPAddress: function(v) {
return /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(v);
},
IPAddressText: 'Must be a numeric IP address',
IPAddressMask: /[\d\.]/i
});

Vous aimerez peut-être aussi