Sunday, December 9, 2012
ExtJS 4–Data Framework–Models-Validation–Part 2
Continuing from previous post. Lets add some validation to the model. Data validation can be specified in models through the validations configuration array. Validation available are
presence | Field has to have a value. Empty strings are not valid. Zero (0) is valid |
length | can be b/w min and max length |
inclusion | set of values |
exclusion | not in a set of values |
format | regular expression format. For example : email format |
Validating Data
We need to call validate() method on the model object to validate. The model object returns a Ext.data.Errors Object. Method in Ext.data.Errors of use are
isValid() | true if there are not errors |
forField(fieldname) | Error objec for the field |
each(function) | iterate over the error object and display the errors |
Let’s see how to validate and get error object next.
Ext.define('Training.model.Person', {
extend:'Ext.data.Model',
fields:[
{
name:'firstname',
type:'string'
},
{
name:'lastname',
type:'string'
},
{
name:'dob',
type:'date',
dateFormat:'m-d-Y'
},
{
name:'single',
type:'boolean'
},
{
name:'gender',
type:'string'
}
],
validations:[
{
type:'presence',
field:'firstname'
},
{
type:'inclusion',
field:'gender',
list:['M', 'F']
}
]
});
var init = function () {
var newPerson = Ext.create('Training.model.Person', {
lastname:'Doe',
dob:'10-21-2001',
single:true,
gender:'do-not-bother'
});
// call the validate() method to check if the model has correct values
var errors = newPerson.validate();
console.log("Errors is "+ errors);
if(!errors.isValid()){
errors.each(function(error){
console.log("Field : "+ error.field+" message : "+ error.message);
})
}
};
Ext.onReady(init);
As we see in above code, we have defined two validation, one for firstname as presence validation and another for gender as inclusion. The inclusion list is specified in array. We are creating a newPerson object in the init function. Wee are not setting value for “firstname” and for gender we are setting some arbitrary value. The validations fail on call to validate(). The errors object is iterated to display individual error. The console displays the following error.
The demo can be found here
Thank you nice explaination on validations..
ReplyDelete