Expert wanna be
Expert wanna be

Reputation: 10624

Backbone.js validate model

I expected, when call model.set() method in view, the validate function should run, but I test with the below code, it never call the validate function that is defined in Model. Anybody know what I am doing wrong?

<!doctype html>
<html>
<head>
  <meta charset=utf-8>
  <title>Form Validation - Model#validate</title>
  <script src='http://code.jquery.com/jquery.js'></script>
  <script src='http://underscorejs.org/underscore.js'></script>
  <script src='http://backbonejs.org/backbone.js'></script>
  <script>
    jQuery(function($) {

      var User = Backbone.Model.extend({
        validate: function(attrs) {
          var errors = this.errors = {};

          console.log('This line is never called!!!');

          if (!attrs.firstname) errors.firstname = 'firstname is required';
          if (!attrs.lastname) errors.lastname = 'lastname is required';
          if (!attrs.email) errors.email = 'email is required';

          if (!_.isEmpty(errors)) return errors;
        }
      });

      var Field = Backbone.View.extend({
        events: {blur: 'validate'},
        initialize: function() {
          this.name = this.$el.attr('name');
          this.$msg = $('[data-msg=' + this.name + ']');
        },
        validate: function() {
          this.model.set(this.name, this.$el.val());
          //this.$msg.text(this.model.errors[this.name] || '');
        }
      });

      var user = new User;

      $('input').each(function() {
        new Field({el: this, model: user});
      });

    });
  </script>
</head>
<body>
  <form>
    <label>First Name</label>
    <input name='firstname'>
    <span data-msg='firstname'></span>
    <br>
    <label>Last Name</label>
    <input name='lastname'>
    <span data-msg='lastname'></span>
    <br>
    <label>Email</label>
    <input name='email'>
    <span data-msg='email'></span>
  </form>
</body>
</html>

Upvotes: 1

Views: 488

Answers (1)

Kevin Peel
Kevin Peel

Reputation: 4090

As of Backbone 0.9.10, validate is only called when saving by default. If you want to have it validate when you're setting attributes, you need to pass the {validate: true} option.

var Field = Backbone.View.extend({
  // ..
  validate: function() {
    this.model.set(this.name, this.$el.val(), {validate: true});
    //this.$msg.text(this.model.errors[this.name] || '');
  }
});

Upvotes: 3

Related Questions