Skip to content

Instantly share code, notes, and snippets.

@fiznool
Created June 4, 2013 07:35
Show Gist options
  • Save fiznool/5704239 to your computer and use it in GitHub Desktop.
Save fiznool/5704239 to your computer and use it in GitHub Desktop.
Module which augments backbone.validator
define(function(require, exports, module) {
var _ = require('lodash');
var Validator = require('backbone.validator');
// Duck-punch so that we get the errors in the right format:
// Instead of
// {
// field1: [ "errormsg1", "errormsg2" ],
// field2: [ "errormsg3" ]
// }
// We want
// [{
// key: "field1",
// msg: "errormsg1"
// }, {
// key: "field1",
// msg: "errormsg2"
// }, {
// key: "field2",
// msg: "errormsg3"
// }]
var originalValidate = Validator.validate;
Validator.validate = function(attrs, validations, context) {
var rtn = null;
var errors = originalValidate.call(Validator, attrs, validations, context);
if(errors) {
rtn = [];
// Transform from object with nested message arrays
// into an array of 'flat' errors
_.each(errors, function(messages, key) {
_.each(messages, function(msg) {
rtn.push({
field: key,
msg: msg
});
});
});
}
return rtn;
};
// Overrides and additions
// Most matchers are from https://github.com/chriso/node-validator
Validator.formats.email = /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/;
Validator.add('notBlank', function(value, expectation) {
return expectation === false || (_.isString(value) && !value.match(/^[\s\t\r\n]*$/));
}, "Can't be blank");
Validator.add('password', function(value, expectation) {
return expectation === false || (_.isString(value) && !value.match(/^[\s\t\r\n]*$/));
}, "Password not valid");
Validator.add('matches', function(value, expectation, attrs) {
return value === attrs[expectation];
}, "Does not match");
});
@fiznool
Copy link
Author

fiznool commented Jun 4, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment