Backbone Forms: Built-in Validators

by Glen Pike

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.3/backbone-min.js"></script>
<script src="https://rawgithub.com/powmedia/backbone-forms/master/distribution/backbone-forms.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">

CSS

div[data-error] {
  color: red;
}

JavaScript

var schema = {
  //Built-in validators
  //required
  name: {
    validators: ['required']
  },
  //number
  amount: {
    validators: ['number']
  },
  //url
  url: {
    validators: ['url']
  },

  //Regular expression
  foo: {
    validators: [/foo/]
  },
  //Regular expression with message
  bar: {
    validators: [{
      type: 'regexp',
      regexp: /bar/,
      message: 'Must type \'bar\''
    }]
  },
  //Regular expression with flags - if using flags, regexp must be string
  baz: {
    validators: [{
      type: 'regexp',
      regexp: 'baz',
      flags: 'i',
      message: 'Must type \'baz\' - case insensitive'
    }]
  },

  //Multiple built-in validators
  email: {
    validators: ['required', 'email']
  },

  //Built-in editors with options:
  //range
  range: {
    validators: [{
      type: 'range',
      min: 10,
      max: 50,
      message: 'A number between 10 and 50'
    }]
  },
  //match
  password: {
    validators: [{
      type: 'match',
      field: 'passwordConfirm',
      message: 'Passwords must match!'
    }]
  },
  passwordConfirm: {
    validators: [{
      type: 'match',
      field: 'password',
      message: 'Passwords must match!'
    }]
  },

  //Custom function
  username: {
    validators: [
      function checkUsername(value, formValues) {
        var err = {
          type: 'username',
          message: 'Usernames must be at least 3 characters long'
        };

        if (value.length < 3) return err;
      }
    ]
  }
}

var form = new Backbone.Form({
  schema: schema,
  submitButton: 'Submit',
  validate: true
}).render().on('submit', function(e) {
  e.preventDefault();
  this.validate();
});

$('body').append(form.el);