2013년 10월 17일 목요일

Applying validation rules to Models' fields

1. We will start this recipe with the Book Model class we defined in the previous recipes:
Ext.define('Book', {
extend: 'Ext.data.Model',
fields: [{
name: 'Title',
type: 'string'
}, {
name: 'Publisher',
type: 'string'
}, {
name: 'ISBN',
type: 'string'
}, {
name: 'PublishDate',
type: 'date',
dateFormat: 'd-m-Y'
}, {
name: 'NumberOfPages',
type: 'int'
}, {
name: 'Read',
type: 'boolean'
}]
});

2. Now we use the validations configuration to define a minimum length of 1 on the
book's title and make the Publisher field mandatory:
Ext.define('Book', {
extend: 'Ext.data.Model',
fields: [{
name: 'Title',
type: 'string'
}, {
name: 'Publisher',
type: 'string'
}, {
name: 'ISBN',
type: 'string'
}, {
name: 'PublishDate',
type: 'date',
dateFormat: 'd-m-Y'
}, {
name: 'NumberOfPages',
type: 'int'
}, {
name: 'Read',
type: 'boolean'
}],
validations: [{
type: 'length',
field: 'Title',
min: 1
}, {
type: 'presence',
field: 'Publisher'
}]
});

Other built-in validators
There are a total of six built-in validators that can be applied to a Model's fields. In our
previous example, we encountered two of them—presence and length. The other four are
outlined as follows:
ff email: validates that the field contains a valid e-mail address
ff exclusion: accepts a list configuration containing an array of values and will
return true if the field's value is not in the list
ff inclusion: identical to exclusion but evaluates to true if the field's value is present
in the list array
ff format: accepts a matcher configuration option that should contain a regex for the
field's value to be matched against

Creating a custom validator
Ext.data.validations.isbnMessage = 'is not a valid ISBN Number';
Ext.data.validations.isbn = function(config, value){
return true;
};
Ext.data.validations.isbn = function(config, value){
var valid = false;
valid = value.length === 17; // 13 digits + 4 hyphens
valid = valid && (value.split('-').length === 5); // contains 4 hyphens
return valid;
};

댓글 없음:

댓글 쓰기