Backbone Validate does not work

后端 未结 4 784
小蘑菇
小蘑菇 2020-12-24 03:00

I am using Backbone\'s validate function to guarantee Man to have an age property more than 18. Here is my code:

var M         


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 03:15

    In Backbone.js (prior to version 0.9.10), validate is called before save as well as before set.

    You will get an alert error when you set invalid value.

    Example - age value is below 18 :

    var man = new Man ({name : 'qian', age : 12});
    man.set({ age: 12 }); // that will trigger alert
    

    EDIT

    For Backbone.js version 0.9.10+ there is an issue reported: Failed validation does not trigger error callback. Issue explanation says that

    invalid event should be used instead of error

    So changing your code to:

    var Man = Backbone.Model.extend({
        initialize : function(){
            this.on("invalid",function(model,error){
                alert(error);
            });
        },
        ...
    

    And setting variable with validate option set to true will trigger an alert.

    man.set({age: 12}, {validate : true});
    

提交回复
热议问题