Sencha Touch : Login Form with Validation
Join the DZone community and get the full member experience.
Join For Free
once user submit form for login, we get the validation logic and see
if all the field get passed against our model validation logic, if no
then will show error message alert and make the field highlighted in red
border. so lets start first by creating
model
. pay attention to
validations
array, its an array of all validation rules that we want to apply for our model fields.
ext.define("techzoo.model.user", { extend: "ext.data.model", config: { fields : [ {name : 'username', type: 'string'}, {name : 'password', type: 'string'} ], validations : [{ type: 'presence', field: 'username', message: 'can not be blank.' },{ type : 'presence', field : 'password', message: 'can not be blank.' },{ type : 'length', field : 'username', min : 6, max : 8, message: 'is not in valid range.' },{ type : 'length', field : 'password', min : 6, max : 8, message: 'is not in valid range.' }] } });now, create a loginform by extending
formpanel
.
ext.define('techzoo.view.loginform', { extend : 'ext.form.panel', alias : 'widget.loginform', config : { fullscreen : true, scroll : 'vertical', url : '', items :[{ xtype : 'fieldset', title : 'enter your login details', items : [{ xtype : 'textfield', labelwidth: 120, label : 'username', name : 'username', required: true },{ xtype : 'passwordfield', label : 'password', labelwidth: 120, name : 'password', required: true }] },{ xtype : 'toolbar', docked : 'bottom', layout : { pack : 'center', type : 'hbox' }, items : [{ text : 'reset', handler: function(me) { var form = me.up('formpanel'); form.reset(); ext.each(form.query('textfield'), function(tf){ tf.removecls('invalidfield'); }); } },{ text : 'login now', ui : 'confirm', handler: function(me) { var form = me.up('formpanel'); var user = ext.create('techzoo.model.user', form.getvalues()); var errors = user.validate(); if(!errors.isvalid()) { var errormsg = ""; errors.each(function (item, index, length) { form.down("field[name='"+item.getfield()+"']").addcls('invalidfield'); errormsg += ' ' +item.getfield()+' '+ item.getmessage() + '<br/>'; }); ext.msg.alert("validation failed", errormsg); } else { ext.msg.alert("validation success", "form doesn't contain any error."); } } }] }] } });
take a close look at login button handler. first, we are creating the model object and then calling
validate()
method on it. calling validate methods return
ext.data.errors
object. we can call
isvalid()
function to see if form contain any error on not.
output:
on initial launch of form…
if form contains any error…
i hope you enjoy the post. happy coding
Opinions expressed by DZone contributors are their own.
Comments