Created
June 4, 2013 07:35
-
-
Save fiznool/5704239 to your computer and use it in GitHub Desktop.
Module which augments backbone.validator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This Backbone.Validator