# Validating a model and focus to the element if validation fails

I am using Backbone Marionette - I would like to set the user name and password if that passes the model validation method.

I am highly confused with that. Please show me a handy approach or correct me if I'm doing this wrong.

define(["backbone"], function(Backbone){
var LoginModel = Backbone.Model.extend({
defaults:{
},
validate:function(attr, options){
}
}
},
initialize:function(){
this.on("invalid", function(model, error){
console.log(model, error); // error consoles 2 times (4 times for both)
});
}
});

});


View.js:

define([
'jQuery','underscore',
'backbone','marionette',
function($,_,Backbone,Marionette,template){ "use strict"; var LoginView = Backbone.Marionette.ItemView.extend({ className:'col-xs-12 col-md-4 col-md-offset-4', template:_.template(template), events:{ "submit form" : "loginSubmit" }, loginSubmit:function(e){ e.preventDefault(); var data = Backbone.Syphon.serialize(e.target), validUser = this.model.set('userName',data.userName, {validate: true}), validPass = this.model.set('password', data.password,{validate: true}); if(!validUser){$(e.target).find('#userName').select();
} else{
$(e.target).find('#userName').next(':input').select(); } if(!validPass){$(e.target).find('#userName').select();
}

}

});

}
);


This works, but I am looking for the best approach.

I'm not very familiar with Backbone, however I do have a couple of comments:

• To simplify your life, check out Marionette Forms. It can handle quick validation of forms. This is an alternative to Backbone Forms, which is generally more demanding in terms of code needed.

• The following snippet:

if(!validUser){
$(e.target).find('#userName').select(); } else{$(e.target).find('#userName').next(':input').select();
}

if(!validPass){
$(e.target).find('#userName').select(); }  could simply be: if (validUser && validPass) {$(e.target).find('#userName').next(':input').select();
} else {