Auto Form-Model Validation
An example of tweaking the form-model relationship to apply model validations to a form
by existdissolve
HTML
<link rel="stylesheet" href="http://cdn.sencha.io/ext-4.1.1-gpl/resources/css/ext-all.css">
JavaScript
Ext.define('Person', {
extend: 'Ext.data.Model',
fields: [
{name:"name", type:'string'},
{name:"age", type:"int"},
{name:"hobby", type:"string"}
],
validations: [
{type: 'presence', field: 'name', message: 'You have to enter a name, silly'},
{type: 'presence', field: 'age', message: 'You must specify an age'},
{type: 'presence', field: 'hobby', message: 'You must enter a hobby'},
{type: 'length', field: 'hobby', min:5, message: 'You must specify a hobby with more than 4 characters'}
]
})
Ext.define('Form', {
extend: 'Ext.form.Panel',
alias: 'widget.peopleform',
bodyPadding: 10,
border: false,
initComponent: function() {
var me = this;
Ext.applyIf(me, {
defaults: {
width: 250,
labelWidth: 70
},
autoShow: true,
renderTo: Ext.getBody(),
items: [
{
xtype: 'textfield',
name: 'name',
fieldLabel: 'Name'
},
{
xtype: 'numberfield',
name: 'age',
fieldLabel: 'Age',
value: 20
},
{
xtype: 'textfield',
name: 'hobby',
fieldLabel: 'Hobby'
}
]
});
me.callParent(arguments);
}
})
Ext.override(Ext.form.Basic, {
loadRecord: function(record) {
this._record = record;
this.setModelValidations(record.validations);
return this.setValues(record.data);
},
setModelValidations: function(validations) {
var fields = this.getFields(), i;
for(i=0;i<validations.length;i++) {
var fieldMatch = this.findField(validations[i].field);
if(fieldMatch) {
...