ExtJS custom textfield validation for natural numbers. Suppose you have a text field on your form like this:
this.portField= Ext.create('Ext.form.field.Text', {
fieldLabel: 'Port',
labelAllign: 'top'
});
And that your goal is to make sure the user enters only a natural number. Here I am referring to a natural number as a non-negative integer.
Your first choice would be to look at the (vtype)[http://docs.sencha.com/ext-js/4-1/#!/api/Ext.form.field.VTypes] config available for the text field. However, you will notice that there is no available choice to mark strictly an integer. That of course, means we get to write our own! Luckily this is not a difficult task:
Ext.apply(Ext.form.field.VTypes, {
natural: function(val, field) {
var reg= /^\d+$/i;
return reg.test(val);
},
naturalText: 'Must be a natural number',
naturalMask: /^[0-9]/i
});
What this does is apply a regular expression to the contents of the field to check for its validity. This statement will actually disallow any non-numeric characters from being entered into the field! The three configs must all start with the same string which will become your new vtype
, here it is natural
. Now we can simply add the new vtype to the text field:
this.portField= Ext.create('Ext.form.field.Text', {
fieldLabel: 'Port',
labelAllign: 'top',
vtype: 'natural'
});