Skip to content

Commit

Permalink
data validation and error display when editing a contact
Browse files Browse the repository at this point in the history
  • Loading branch information
davidsulc committed Oct 22, 2013
1 parent 494c86c commit d5f1112
Show file tree
Hide file tree
Showing 5 changed files with 523 additions and 2 deletions.
9 changes: 9 additions & 0 deletions assets/js/apps/contacts/edit/edit_controller.js
Expand Up @@ -14,6 +14,15 @@ ContactManager.module("ContactsApp.Edit", function(Edit, ContactManager, Backbon
view = new Edit.Contact({
model: contact
});

view.on("form:submit", function(data){
if(contact.save(data)){
ContactManager.trigger("contact:show", contact.get("id"));
}
else{
view.triggerMethod("form:data:invalid", contact.validationError);
}
});
}
else{
view = new ContactManager.ContactsApp.Show.MissingContact();
Expand Down
26 changes: 25 additions & 1 deletion assets/js/apps/contacts/edit/edit_view.js
Expand Up @@ -8,7 +8,31 @@ ContactManager.module("ContactsApp.Edit", function(Edit, ContactManager, Backbon

submitClicked: function(e){
e.preventDefault();
console.log("edit contact");
var data = Backbone.Syphon.serialize(this);
this.trigger("form:submit", data);
},

onFormDataInvalid: function(errors){
var $view = this.$el;

var clearFormErrors = function(){
var $form = $view.find("form");
$form.find(".help-inline.error").each(function(){
$(this).remove();
});
$form.find(".control-group.error").each(function(){
$(this).removeClass("error");
});
}

var markErrors = function(value, key){
var $controlGroup = $view.find("#contact-" + key).parent();
var $errorEl = $("<span>", { class: "help-inline error", text: value });
$controlGroup.append($errorEl).addClass("error");
}

clearFormErrors();
_.each(errors, markErrors);
}
});
});
20 changes: 19 additions & 1 deletion assets/js/entities/contact.js
@@ -1,6 +1,24 @@
ContactManager.module("Entities", function(Entities, ContactManager, Backbone, Marionette, $, _){
Entities.Contact = Backbone.Model.extend({
urlRoot: "contacts"
urlRoot: "contacts",

validate: function(attrs, options) {
var errors = {}
if (! attrs.firstName) {
errors.firstName = "can't be blank";
}
if (! attrs.lastName) {
errors.lastName = "can't be blank";
}
else{
if (attrs.lastName.length < 2) {
errors.lastName = "is too short";
}
}
if( ! _.isEmpty(errors)){
return errors;
}
}
});

Entities.configureStorage(Entities.Contact);
Expand Down

0 comments on commit d5f1112

Please sign in to comment.