JSFiddle - React, Tailwind, and code Playground
by rjzaworski
JavaScript
var validators = {
presence: function (attrs, key, present) {
if (typeof(present) == 'undefined') {
present = true;
}
return (attrs.hasOwnProperty(key) == present && attrs[key] == present);
},
match: function (attrs, key, test) {
if (test instanceof RegExp) {
return attrs[key].match(test);
}
return attrs[key] == test;
},
confirm: function (attrs, key, otherKey) {
return attrs[key] == attrs[otherKey];
},
maxLength: function (attrs, key, len) {
return attrs[key].length < len;
},
minLength: function (attrs, key, len) {
return attrs[key].length > len;
}
};
function validateAttributes (attributes, validations) {
var options, rule, validator, errors = {};
for (key in validations) {
rule = validations[key];
for (validator in rule) {
options = validator[rule];
if (!(options instanceof Array)) options = [options];
if (!validators[validator].apply(this, [attributes, key].concat(options))) {
errors[key] = rule;
}
}
}
}
// The validations
var validations = {
email: { type: 'email' },
name: { presence: true, },
password: { presence: true },
confirm: { confirm: 'password' }
};
// The model itself
var MyModel = Backbone.Model.extend({
validate: function (attributes) {
return validateAttributes(attributes, validations);
}
});
var m = new MyModel({
email: '[email protected]',
name: 'Foobar',
password: 'password',
confirm: 'password'
});
console.log(m.isValid());