Skip to content

Instantly share code, notes, and snippets.

@flexdevguy
Created September 15, 2016 08:40
Show Gist options
  • Select an option

  • Save flexdevguy/abfb10350c57d751cbd7adee4b8c2562 to your computer and use it in GitHub Desktop.

Select an option

Save flexdevguy/abfb10350c57d751cbd7adee4b8c2562 to your computer and use it in GitHub Desktop.
Extjs Form Field Validation using View model links.
//--------------------------------------
// UI
//--------------------------------------
/**
* @class com.flexdevguy.view.FieldValidator
* @extends Ext.Component
* Form field validator
*/
Ext.define('com.flexdevguy.view.FieldValidator', {
extend: 'Ext.Component',
requires: [
'com.flexdevguy.viewmodel.FieldValidator',
'com.flexdevguy.model.FieldValidator',
'com.flexdevguy.controller.FieldValidatorController'
],
controller: 'fieldvalidatorcontroller',
viewModel: {
type: 'fieldvalidator'
},
items: [{
xtype: 'formpanel',
defaultType: 'textfield',
items: [{
label: 'User Name',
bind: '{linkName.userName}'
}, {
label: 'Password',
bind: '{linkName.password}'
}],
}],
});
//--------------------------------------
// View Model
//--------------------------------------
Ext.define('com.flexdevguy.viewmodel.FieldValidator', {
extend: 'Ext.app.ViewModel',
xtype: 'fieldvalidator',
links: {
linkName: {
reference: 'com.flexdevguy.model.FieldValidator',
create: true
}
}
});
//--------------------------------------
// Model
//--------------------------------------
Ext.define('com.flexdevguy.model.FieldValidator', {
extend: 'Ext.data.Model',
alias: 'model.modelname',
requires: [
'com.flexdevguy.viewmodel.FieldValidator',
],
fields: [{
name: 'userName',
type: 'string',
defaultValue: ''
}, {
name: 'password',
type: 'string'
},{
xtype:'button',
listeners:{
tap: 'validateForm'
}
}],
validators: {
//this name should match the fields name
userName: {
type: 'email', //type may be length or email or presence or format or bound or inclusion or exclusion
message: 'Please enter valid email address'
},
password: {
type: 'length',
min: 5,
message: 'You password length mist be minimum five characters'
}
}
});
//--------------------------------------
// Controller
//--------------------------------------
/**
* @class com.flexdevguy.controller.FieldValidatorController
* @extends Ext.app.ViewController
* Description
*/
Ext.define('com.flexdevguy.controller.FieldValidatorController', {
extend: 'Ext.app.ViewController',
alias: 'controller.fieldvalidatorcontroller',
validateForm: function() {
var vm = this.getViewModel();
if (!vm.get('linkName').isValid()) {
var validatorResult = vm.get('linkName').validate();
var errors = validatorResult.items;
for (var i = 0; i < errors.length; i++) {
console.log('Key :' + errors[i].field + ' , Message :' + errors[i].msg);
};
} else {
console.log('Form is Valid');
}
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment