backbone.js - Backbone.Model validation and isValid -
i have set model validation below
- full coffeescript code: http://pastebin.com/3iszzke8
- demo on js fiddle: http://jsfiddle.net/xktnb/
model's validation
class todo extends backbone.model validate: (attrs) -> errs = {} haserrors = false if (attrs.title "") haserrors = true errs.title = "please specify todo" if haserrors return errs error related code in view
class todoview extends backbone.view events: "keypress .editing input[name=todo]": "savetodo" "keyup .editing input[name=todo]": "closeedit" "blur input[name=todo]": "clearerrors" initialize: -> ... @model.bind("change", @render) @model.bind("error", @handleerror) savetodo: (e) -> if e.type "keypress" , e.charcode isnt 13 return @model.set("title": @$("input[name=todo]").val()) console.log @$("input[name=todo]").val() + "...", @model.isvalid(), @model.get("title") if @model.isvalid() @closeedit() closeedit: (e) -> if (e) if e.type "keyup" , e.keycode isnt 27 return @$el.removeclass("editing") handleerror: (model, errs) -> @clearerrors() @$("input[name=todo]").after($("<span />", { class: "error", html: errs.title })); console.log "error handled" clearerrors: -> @$el.remove(".error") in todoview.savetodo, check if model valid, if so, expect save successful , want out of edit edit mode. however, appears isvalid true, maybe because validation occurs , model not saved in valid state?
update
added link js fiddle above. try adding todo, try make todo blank. notice closes edit mode although in code had:
savetodo: (e) -> if e.type "keypress" , e.charcode isnt 13 return @model.set("title", @$("input[name=todo]").val()) if @model.isvalid() # model appears valid here! @model.save() @closeedit() now double click go edit mode, notice error there meaning validation done correctly
i don't understand question read have model in try save information you've entered.
the models validate method automatically return error on setting values of model.
for instance:
var todomodel = backbone.model.extend({ defaults: { title: '', closed: 'false' }, validate: function(attr) { if (attr.title === '') { console.log("title expected"); } } }); now when create new instance of object (so did not save information in model yet) model isvalid return false:
var todo = new todomodel(); console.log(todo.isvalid()); //will false i don't know got save function from. if place data todo model can this:
var todo = new todomodel(); todo.set({ 'title': 'figure out backbone js' }); console.log(todo.isvalid()); //must return true of course can set these values imediatly:
var todo = new todomodel({ 'title': 'still figuring out' }); console.log(todo.isvalid()); //still returns true so way validation checking.
Comments
Post a Comment