我无法在Backbone.js中执行验证

I am unable to execute validation in Backbone.js.

本文关键字:执行 验证 js Backbone      更新时间:2023-09-26

每当我将age属性设置为负值时,它都不会返回false。我也尝试过在控制台中执行这个代码,但仍然没有发生任何事情

<script>
        var Human = Backbone.Model.extend({
      // If you return a string from the validate function,
      // Backbone will throw an error
      defaults: {
        name: 'Guest user',
        age: 23,
        occupation: 'worker'
      },
      validate: function( attributes ){
        if( attributes.age < 0){
            return "Age must me positive";
        }
        if( !attributes.name ){
            return 'Every person must have a name';
        }
      },
     work: function(){
      return this.get('name') + ' is working';
       }
     });

      var human = new Human;
      human.set("age", -10);  
    human.on('error', function(model, error){
        console.log(error);
      });
    </script>

您的代码有一些错误:

  1. 验证的事件是invaliderror用于ajax请求
  2. 默认情况下不会对集合进行验证,您需要将{ validate: true }作为一个选项进行传递
  3. 您正在侦听事件AFTER设置,因此不会为该设置调用它

即:

human.on('invalid', function(model, error) {
  console.log(error);
});
human.set("age", -10, { validate: true });