During my time using CanJS I haven’t found a canonical way of doing form validations with it, so here I want to share the way I am doing them at the moment.
This model is using the validation plug-in to mix-in the validation functions.
Then we need a control:
123456789101112131415161718192021222324252627
varControl=can.Control({init:function(ele,options){this.person=newPerson();this.errors=newcan.Map();varargs={person:this.person,errors:this.errors};varview=can.view('view',args);this.element.html(view);},'form submit':function(){// get errors from person if anyvarerrors=this.person.errors();// pass the errors to our errors observablethis.errors.attr(errors,true);if(errors){console.log(errors);}else{// proceed to saving here}returnfalse;}});
Note how I create a errors can.Map and pass it to the view. This map will allow me to show any validation errors to the user. In form submit we retrieve the errors from the form (using the validation plug-in) and pass those errors to the errors can.Map.