I am using thedersen’s Backbone.validation plugin to provide validation.
The validation itself works so far and gets executed when I submit the form. I only don’t success about letting the view listen on validation errors.
The howto says that you can listen on validation events with:
model.bind('validated:invalid', function(model, attrs) {
// do something
});
Source: http://thedersen.com/backbone.validation/#events/validated
define(['jquery', 'underscore', 'backbone', "models/security/user", 'text!templates/security/registration.html'], function($, _, Backbone, SecurityUserModel, Template){
var SecurityRegistrationView;
SecurityRegistrationView = Backbone.View.extend({
initialize: function(){
this.model = new SecurityUserModel();
this.render();
Backbone.Validation.bind(this);
},
render: function(){
$(this.el).append(Template);
},
events: {
"submit form": "submit"
, "validated:valid": "valid"
, "validated:invalid": "invalid"
},
submit: function(e){
e.preventDefault();
var username, email, password;
username = $("#_user_username").val();
email = $("#_user_email").val();
password = $("#_user_password").val();
this.model.set('username', username);
this.model.set('email', email);
this.model.set('password', password);
this.model.validate();
console.log(this.model.validate());
},
invalid: function(){
$("input").addClass("inputError");
alert(" ");
},
valid: function(){
alert(" ");
this.model.save(function(){
// server validation callback...
});
}
});
return SecurityRegistrationView;
});
So how can I use the model related event in a form?
The events
validated:validandvalidated:invalidare not DOM-events, but Backbone events. TheBackbone.Viewevents hash is meant for handling DOM-events (source) whereas themodel.bindis used to tap onto events triggered by the particular model.So remove these lines from the events-hash:
and add this to your initialize function
Now you are tapping into the model events the correct way.
Hope this helps!