ok

Simple object validation

ok.js

Simple validation library for Javascript models. It doesn't touch the DOM, it doesn't return messages. It just takes an object and validates it against a set of rules returning an object for working with errors.

I wasn't happy with the validation libraries available for Backbone models. Most are large and try and do too much. Ok was designed to take your models attributes and return a nice error object that your views can use to update your UI. It doesn't attempt to cover every validation use-case but it provides a simple interface for extending the validation rules available.

  • Provide an easy interface for extending the validation rules
  • Common and basic validation rules included by default
  • Doesn't show errors or make DOM changes like jQuery.validate
  • Doesn't handle messages of any kind
  • Doesn't provide complex validation rules
  • Underscore.js

Download the production version or the development version.

var schema = new OK({
  first_name: {
    required: true,
    string: true
  },
  last_name: {
    required: true,
    string: true
  },
  birthday: {
    date: true
  }
});
 
var errors = schema.validate({
  first_name: "Naruto",
  birthday: '4 Jan 1988'
});
 
// Any errors? 
if( errors.length === 0 ) {
  return "Hooray!";
}
 
// Loop through all of the errors easily 
errors.each(function(listattr){
  // list is an array of rules that didn't validate from the schema 
  // attr is the attribute that failed 
});
var Person = Backbone.Model.extend({
  validates: {
    first_name: {
      required: true,
      string: true
    },
    last_name: {
      required: true,
      string: true
    }
  },
  validatefunction(attrsoptions) {
    this.errors = OK.validate(attrs, this.validates);
    return this.errors.length > 0 ? this.errors : null;
  }
});

The built-in rules will example usage.

Accepts a boolean value

name: {
  required: true
}

Basic email check. It's not a complex email regex but it will cover the majority of cases. Accepts true or false.

email: {
  email: true
}

Basic URL check. Accepts true or false.

blog: {
  url: true
}

Accepts a string with numbers or letters. A simple /^\w+$/ check. Accepts true or false.

username: {
  alphanumeric: true
}

Accepts a hex value with or without the leading hash. Accepts true or false.

color: {
  hex: true
}

Check if a value is a string using underscores _.isString method. Accepts true or false.

title: {
  string: true
}

Check if a value is a number. Strings that return a number with parseFloat will pass. Accepts true or false.

user_id: {
  number: true
}

Check if a value is a string using underscores _.isArray method. Accepts true or false.

entries: {
  array: true
}

Simple date checking using Date.parse or _.isDate. Accepts true or false.

due_at: {
  date: true
}

Check if a value is a string using underscores _.isBoolean method. Accepts true or false.

terms: {
  boolean: true
}

Limit a number to a max value.

size: {
  max: 1000
}

Limit a number to a min value.

size: {
  min: 1
}

Check the length property of an object.

account_id: {
  length: 14
}

Check the length property of an object.

account_id: {
  minlength: 14
}

Check the length property of an object.

account_id: {
  maxlength: 14
}

Check the value equals the other object using _.isEqual.

equal: {
  secret: 'nyan'
}

Check that the number is within a range. Takes an object with a from and to value.

level: {
  range: {
    from: 0,
    to: 3
  }
}

Checks to see if the value is any value in an array.

level: {
  in: [0, 1, 3]
}

Tests the value against the regex object.

name: {
  pattern: /^foo/
}

You can define a custom validator within your schema by passing a function as the value for a rule. For example:

var schema = {
  passwordfunction(valuedata) {
    return value === data.password_confirm;
  }
};

The function is passed the value being checked and the whole object of data being checked so you can do comparisons on other attributes.

The schema is just a simple object with keys that map to attributes. The values are a hash of rules. The key is the validation type and the value will be passed to the validation method in OK.Validator. For example

var schema = {
  name: {
    string: true
  }
};

This object can be passed to OK.validate(attributes, schema) to be used once or you can contruct a new OK instance new OK(schema) and reuse the same schema validation across your application.

Whenever you validate you are returned an OK.Error object. This is a simple interface for working with the errors.

The total number of errors for all attributes. This is the easiest way to check if there are any errors.

var errors = OK.validate(attrs, schema);
if( errors.length > 0 ) {
  // Update view 
}

Check if an attribute that was passed in was valid.

Returns the errors object for an attribute or false if there is no errors for that attribute

Loop through the errors for an attribute and call the callback. If the attr param is omitted and a function is passed in as the only parameter it will loop through the errors object itself so you can check each of the attributes.

Similar the implementation in Backbone. Returns an object of errors that can be used as JSON.

Adding new validation rules is just a matter of adding a new method to the prototype of OK.Validator

OK.Validator.prototype.creditcard = function(valueoptionsdata){
  return CreditCard.check(value, options);
};

The function will be passed the value, the options for that rule (which is whatever you've defined in your schema) and the object of all the data that is being validated so you can check the value in relation to other values. Here's an example schema using the validation method we just defined:

var schema = {
  card: {
    creditcard: {
      type: 'mastercard'
    }
  }
};
 
var data = {
  card: 'foo'
};
 
OK.validate(data, schema);

In the validtion method, value will be 'foo', options will be { type: mastercard } and data will be the object that is passed in to validate.

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using grunt.

Also, please don't edit files in the "dist" subdirectory as they are generated via grunt. You'll find source code in the "lib" subdirectory!

0.1.0 - First release

Copyright (c) 2012 Anthony Short
Licensed under the MIT license.