loopback-datasource-juggler/lib/validations.js

612 lines
15 KiB
JavaScript
Raw Normal View History

var util = require('util');
2013-04-11 23:23:34 +00:00
/**
* Module exports
*/
2013-04-04 15:31:07 +00:00
exports.ValidationError = ValidationError;
2011-10-10 13:22:51 +00:00
2012-03-27 14:22:24 +00:00
/**
2013-04-11 23:23:34 +00:00
* Validation mixins for model.js
2012-03-27 14:22:24 +00:00
*
* Basically validation configurators is just class methods, which adds validations
* configs to AbstractClass._validations. Each of this validations run when
* `obj.isValid()` method called.
*
* Each configurator can accept n params (n-1 field names and one config). Config
* is {Object} depends on specific validation, but all of them has one common part:
* `message` member. It can be just string, when only one situation possible,
* e.g. `Post.validatesPresenceOf('title', { message: 'can not be blank' });`
*
* In more complicated cases it can be {Hash} of messages (for each case):
* `User.validatesLengthOf('password', { min: 6, max: 20, message: {min: 'too short', max: 'too long'}});`
*/
2013-05-28 05:20:30 +00:00
exports.Validatable = Validatable;
function Validatable() {
}
2011-10-10 13:22:51 +00:00
2012-03-27 14:22:24 +00:00
/**
* Validate presence. This validation fails when validated field is blank.
*
* Default error message "can't be blank"
*
2012-03-27 19:48:23 +00:00
* @example presence of title
* ```
* Post.validatesPresenceOf('title');
* ```
* @example with custom message
* ```
* Post.validatesPresenceOf('title', {message: 'Can not be blank'});
* ```
*
2012-03-27 14:22:24 +00:00
* @sync
*
* @nocode
* @see helper/validatePresence
*/
2011-10-10 13:22:51 +00:00
Validatable.validatesPresenceOf = getConfigurator('presence');
2012-03-27 14:22:24 +00:00
/**
* Validate length. Three kinds of validations: min, max, is.
*
* Default error messages:
*
* - min: too short
* - max: too long
* - is: length is wrong
*
2012-03-27 19:48:23 +00:00
* @example length validations
* ```
* User.validatesLengthOf('password', {min: 7});
* User.validatesLengthOf('email', {max: 100});
* User.validatesLengthOf('state', {is: 2});
* User.validatesLengthOf('nick', {min: 3, max: 15});
* ```
* @example length validations with custom error messages
* ```
* User.validatesLengthOf('password', {min: 7, message: {min: 'too weak'}});
* User.validatesLengthOf('state', {is: 2, message: {is: 'is not valid state name'}});
* ```
2012-03-27 14:22:24 +00:00
*
2012-03-27 19:48:23 +00:00
* @sync
2012-03-27 14:22:24 +00:00
* @nocode
* @see helper/validateLength
*/
2011-10-10 13:22:51 +00:00
Validatable.validatesLengthOf = getConfigurator('length');
2012-03-27 14:22:24 +00:00
/**
* Validate numericality.
*
2012-03-27 19:48:23 +00:00
* @example
* ```
* User.validatesNumericalityOf('age', { message: { number: '...' }});
* User.validatesNumericalityOf('age', {int: true, message: { int: '...' }});
* ```
2012-03-27 14:22:24 +00:00
*
* Default error messages:
*
* - number: is not a number
* - int: is not an integer
*
* @sync
* @nocode
* @see helper/validateNumericality
*/
2011-10-10 13:22:51 +00:00
Validatable.validatesNumericalityOf = getConfigurator('numericality');
2012-03-27 14:22:24 +00:00
/**
* Validate inclusion in set
*
2012-03-27 19:48:23 +00:00
* @example
* ```
* User.validatesInclusionOf('gender', {in: ['male', 'female']});
* User.validatesInclusionOf('role', {
* in: ['admin', 'moderator', 'user'], message: 'is not allowed'
* });
* ```
2012-03-27 14:22:24 +00:00
*
* Default error message: is not included in the list
*
2012-03-27 19:48:23 +00:00
* @sync
2012-03-27 14:22:24 +00:00
* @nocode
* @see helper/validateInclusion
*/
2011-10-10 13:22:51 +00:00
Validatable.validatesInclusionOf = getConfigurator('inclusion');
2012-03-27 14:22:24 +00:00
/**
* Validate exclusion
*
* @example `Company.validatesExclusionOf('domain', {in: ['www', 'admin']});`
*
* Default error message: is reserved
*
* @nocode
* @see helper/validateExclusion
*/
2011-10-10 13:22:51 +00:00
Validatable.validatesExclusionOf = getConfigurator('exclusion');
2012-03-27 14:22:24 +00:00
/**
* Validate format
*
* Default error message: is invalid
*
* @nocode
* @see helper/validateFormat
*/
2011-10-10 17:34:50 +00:00
Validatable.validatesFormatOf = getConfigurator('format');
2012-03-27 14:22:24 +00:00
/**
* Validate using custom validator
*
* Default error message: is invalid
*
2013-02-12 09:05:04 +00:00
* Example:
*
* User.validate('name', customValidator, {message: 'Bad name'});
* function customValidator(err) {
* if (this.name === 'bad') err();
* });
* var user = new User({name: 'Peter'});
* user.isValid(); // true
* user.name = 'bad';
* user.isValid(); // false
*
2012-03-27 14:22:24 +00:00
* @nocode
* @see helper/validateCustom
*/
2011-11-18 18:59:46 +00:00
Validatable.validate = getConfigurator('custom');
2012-03-27 14:22:24 +00:00
/**
* Validate using custom async validator
*
* Default error message: is invalid
*
2013-02-12 09:05:04 +00:00
* Example:
*
* User.validateAsync('name', customValidator, {message: 'Bad name'});
* function customValidator(err, done) {
* process.nextTick(function () {
* if (this.name === 'bad') err();
* done();
* });
* });
* var user = new User({name: 'Peter'});
* user.isValid(); // false (because async validation setup)
* user.isValid(function (isValid) {
* isValid; // true
* })
* user.name = 'bad';
* user.isValid(); // false
* user.isValid(function (isValid) {
* isValid; // false
* })
*
2012-03-27 14:22:24 +00:00
* @async
* @nocode
* @see helper/validateCustom
*/
2011-11-19 05:43:02 +00:00
Validatable.validateAsync = getConfigurator('custom', {async: true});
2012-03-27 14:22:24 +00:00
/**
* Validate uniqueness
*
* Default error message: is not unique
*
* @async
* @nocode
* @see helper/validateUniqueness
*/
2011-11-19 08:58:49 +00:00
Validatable.validatesUniquenessOf = getConfigurator('uniqueness', {async: true});
2011-10-10 13:22:51 +00:00
2011-10-11 19:52:03 +00:00
// implementation of validators
2012-03-27 14:22:24 +00:00
/**
* Presence validator
*/
function validatePresence(attr, conf, err) {
if (blank(this[attr])) {
err();
}
}
2011-10-11 19:52:03 +00:00
2012-03-27 14:22:24 +00:00
/**
* Length validator
*/
function validateLength(attr, conf, err) {
if (nullCheck.call(this, attr, conf, err)) return;
2011-10-11 19:52:03 +00:00
2012-03-27 14:22:24 +00:00
var len = this[attr].length;
if (conf.min && len < conf.min) {
err('min');
}
if (conf.max && len > conf.max) {
err('max');
}
if (conf.is && len !== conf.is) {
err('is');
}
}
2011-10-11 19:52:03 +00:00
2012-03-27 14:22:24 +00:00
/**
* Numericality validator
*/
function validateNumericality(attr, conf, err) {
if (nullCheck.call(this, attr, conf, err)) return;
2011-10-11 19:52:03 +00:00
2012-03-27 14:22:24 +00:00
if (typeof this[attr] !== 'number') {
return err('number');
}
if (conf.int && this[attr] !== Math.round(this[attr])) {
return err('int');
}
}
/**
* Inclusion validator
*/
function validateInclusion(attr, conf, err) {
if (nullCheck.call(this, attr, conf, err)) return;
if (!~conf.in.indexOf(this[attr])) {
err()
}
}
/**
* Exclusion validator
*/
function validateExclusion(attr, conf, err) {
if (nullCheck.call(this, attr, conf, err)) return;
if (~conf.in.indexOf(this[attr])) {
err()
}
}
/**
* Format validator
*/
function validateFormat(attr, conf, err) {
if (nullCheck.call(this, attr, conf, err)) return;
if (typeof this[attr] === 'string') {
if (!this[attr].match(conf['with'])) {
2011-10-11 19:52:03 +00:00
err();
}
2012-03-27 14:22:24 +00:00
} else {
err();
2011-10-11 19:52:03 +00:00
}
2012-03-27 14:22:24 +00:00
}
/**
* Custom validator
*/
function validateCustom(attr, conf, err, done) {
2013-01-30 16:08:52 +00:00
conf.customValidator.call(this, err, done);
2012-03-27 14:22:24 +00:00
}
2011-10-11 19:52:03 +00:00
2012-03-27 14:22:24 +00:00
/**
* Uniqueness validator
*/
function validateUniqueness(attr, conf, err, done) {
var cond = {where: {}};
cond.where[attr] = this[attr];
this.constructor.find(cond, function (error, found) {
if (error) {
return err();
}
2012-03-27 14:22:24 +00:00
if (found.length > 1) {
err();
2013-01-22 20:22:48 +00:00
} else if (found.length === 1 && (!this.id || !found[0].id || found[0].id.toString() != this.id.toString())) {
2012-03-27 14:22:24 +00:00
err();
}
done();
}.bind(this));
}
var validators = {
presence: validatePresence,
length: validateLength,
numericality: validateNumericality,
inclusion: validateInclusion,
exclusion: validateExclusion,
format: validateFormat,
custom: validateCustom,
uniqueness: validateUniqueness
};
2011-10-11 19:52:03 +00:00
2011-11-18 18:59:46 +00:00
function getConfigurator(name, opts) {
2011-10-10 13:22:51 +00:00
return function () {
2011-11-18 18:59:46 +00:00
configure(this, name, arguments, opts);
2011-10-10 13:22:51 +00:00
};
}
2012-03-27 14:22:24 +00:00
/**
* This method performs validation, triggers validation hooks.
* Before validation `obj.errors` collection cleaned.
* Each validation can add errors to `obj.errors` collection.
* If collection is not blank, validation failed.
*
* @warning This method can be called as sync only when no async validation
* configured. It's strongly recommended to run all validations as asyncronous.
2012-03-27 14:22:24 +00:00
*
* @param {Function} callback called with (valid)
* @return {Boolean} true if no async validation configured and all passed
*
* @example ExpressJS controller: render user if valid, show flash otherwise
* ```
* user.isValid(function (valid) {
* if (valid) res.render({user: user});
* else res.flash('error', 'User is not valid'), console.log(user.errors), res.redirect('/users');
* });
* ```
*/
Validatable.prototype.isValid = function (callback, data) {
2011-11-19 05:43:02 +00:00
var valid = true, inst = this, wait = 0, async = false;
2011-10-11 19:52:03 +00:00
// exit with success when no errors
2011-10-10 13:22:51 +00:00
if (!this.constructor._validations) {
2011-10-11 19:52:03 +00:00
cleanErrors(this);
2011-11-19 08:58:49 +00:00
if (callback) {
this.trigger('validate', function (validationsDone) {
validationsDone.call(inst, function() {
callback(valid);
});
});
2011-11-19 08:58:49 +00:00
}
2011-10-10 13:22:51 +00:00
return valid;
}
2011-10-11 19:52:03 +00:00
2011-10-10 13:22:51 +00:00
Object.defineProperty(this, 'errors', {
enumerable: false,
configurable: true,
value: new Errors
});
2011-10-11 19:52:03 +00:00
this.trigger('validate', function (validationsDone) {
var inst = this,
asyncFail = false;
this.constructor._validations.forEach(function (v) {
2011-11-19 05:43:02 +00:00
if (v[2] && v[2].async) {
async = true;
wait += 1;
process.nextTick(function () {
validationFailed(inst, v, done);
});
2011-11-19 05:43:02 +00:00
} else {
if (validationFailed(inst, v)) {
valid = false;
}
}
2011-11-20 08:26:36 +00:00
});
2011-11-19 05:43:02 +00:00
2011-12-09 15:23:29 +00:00
if (!async) {
2013-03-31 09:41:02 +00:00
validationsDone.call(inst, function() {
if (valid) cleanErrors(inst);
if (callback) {
callback(valid);
}
});
2011-12-09 15:23:29 +00:00
}
2011-11-20 08:26:36 +00:00
function done(fail) {
asyncFail = asyncFail || fail;
2013-03-31 09:41:02 +00:00
if (--wait === 0) {
2011-11-20 08:26:36 +00:00
validationsDone.call(inst, function () {
if (valid && !asyncFail) cleanErrors(inst);
2013-03-31 09:41:02 +00:00
if (callback) {
callback(valid && !asyncFail);
}
2011-11-20 08:26:36 +00:00
});
}
2011-11-19 05:43:02 +00:00
}
2011-11-20 08:26:36 +00:00
}, data);
2011-11-19 05:43:02 +00:00
2013-04-01 16:08:22 +00:00
if (async) {
// in case of async validation we should return undefined here,
// because not all validations are finished yet
return;
} else {
return valid;
2011-11-25 15:43:50 +00:00
}
2011-11-19 05:43:02 +00:00
2011-10-10 13:22:51 +00:00
};
2011-10-11 19:52:03 +00:00
function cleanErrors(inst) {
Object.defineProperty(inst, 'errors', {
enumerable: false,
configurable: true,
value: false
});
}
2011-11-19 05:43:02 +00:00
function validationFailed(inst, v, cb) {
2011-10-10 13:22:51 +00:00
var attr = v[0];
var conf = v[1];
2011-11-18 18:59:46 +00:00
var opts = v[2] || {};
if (typeof attr !== 'string') return false;
2011-10-11 19:52:03 +00:00
2011-10-10 13:22:51 +00:00
// here we should check skip validation conditions (if, unless)
// that can be specified in conf
2011-10-11 19:52:03 +00:00
if (skipValidation(inst, conf, 'if')) return false;
if (skipValidation(inst, conf, 'unless')) return false;
2011-10-10 13:22:51 +00:00
var fail = false;
2011-11-18 18:59:46 +00:00
var validator = validators[conf.validation];
var validatorArguments = [];
validatorArguments.push(attr);
validatorArguments.push(conf);
validatorArguments.push(function onerror(kind) {
2013-04-04 15:31:07 +00:00
var message, code = conf.validation;
2011-10-10 13:22:51 +00:00
if (conf.message) {
message = conf.message;
}
if (!message && defaultMessages[conf.validation]) {
message = defaultMessages[conf.validation];
}
if (!message) {
message = 'is invalid';
}
if (kind) {
2013-04-04 15:31:07 +00:00
code += '.' + kind;
2011-10-10 13:22:51 +00:00
if (message[kind]) {
// get deeper
message = message[kind];
} else if (defaultMessages.common[kind]) {
message = defaultMessages.common[kind];
2013-03-26 00:41:00 +00:00
} else {
message = 'is invalid';
2011-10-10 13:22:51 +00:00
}
}
2013-04-04 15:31:07 +00:00
inst.errors.add(attr, message, code);
2011-10-10 13:22:51 +00:00
fail = true;
});
2011-11-19 05:43:02 +00:00
if (cb) {
validatorArguments.push(function () {
cb(fail);
});
}
2011-11-18 18:59:46 +00:00
validator.apply(inst, validatorArguments);
2011-10-10 13:22:51 +00:00
return fail;
}
2011-10-11 19:52:03 +00:00
function skipValidation(inst, conf, kind) {
var doValidate = true;
if (typeof conf[kind] === 'function') {
doValidate = conf[kind].call(inst);
if (kind === 'unless') doValidate = !doValidate;
} else if (typeof conf[kind] === 'string') {
if (typeof inst[conf[kind]] === 'function') {
2011-10-11 19:52:03 +00:00
doValidate = inst[conf[kind]].call(inst);
if (kind === 'unless') doValidate = !doValidate;
} else if (inst.__data.hasOwnProperty(conf[kind])) {
doValidate = inst[conf[kind]];
if (kind === 'unless') doValidate = !doValidate;
2011-10-11 19:52:03 +00:00
} else {
doValidate = kind === 'if';
}
}
return !doValidate;
}
2011-10-10 13:22:51 +00:00
var defaultMessages = {
presence: 'can\'t be blank',
length: {
min: 'too short',
max: 'too long',
is: 'length is wrong'
},
common: {
blank: 'is blank',
'null': 'is null'
},
numericality: {
'int': 'is not an integer',
'number': 'is not a number'
},
inclusion: 'is not included in the list',
2011-11-19 08:58:49 +00:00
exclusion: 'is reserved',
uniqueness: 'is not unique'
2011-10-10 13:22:51 +00:00
};
2011-10-10 17:34:50 +00:00
function nullCheck(attr, conf, err) {
var isNull = this[attr] === null || !(attr in this);
if (isNull) {
if (!conf.allowNull) {
err('null');
}
return true;
} else {
if (blank(this[attr])) {
if (!conf.allowBlank) {
err('blank');
}
return true;
}
}
return false;
}
2012-03-27 14:22:24 +00:00
/**
* Return true when v is undefined, blank array, null or empty string
* otherwise returns false
*
* @param {Mix} v
* @returns {Boolean} whether `v` blank or not
*/
2011-10-10 13:22:51 +00:00
function blank(v) {
if (typeof v === 'undefined') return true;
if (v instanceof Array && v.length === 0) return true;
if (v === null) return true;
if (typeof v == 'string' && v === '') return true;
return false;
}
2011-11-18 18:59:46 +00:00
function configure(cls, validation, args, opts) {
if (!cls._validations) {
Object.defineProperty(cls, '_validations', {
2011-10-10 13:22:51 +00:00
writable: true,
configurable: true,
enumerable: false,
value: []
});
}
args = [].slice.call(args);
var conf;
if (typeof args[args.length - 1] === 'object') {
conf = args.pop();
} else {
conf = {};
}
2011-11-18 18:59:46 +00:00
if (validation === 'custom' && typeof args[args.length - 1] === 'function') {
conf.customValidator = args.pop();
}
2011-10-10 13:22:51 +00:00
conf.validation = validation;
args.forEach(function (attr) {
2011-11-18 18:59:46 +00:00
cls._validations.push([attr, conf, opts]);
2011-10-10 13:22:51 +00:00
});
}
function Errors() {
2013-04-04 15:31:07 +00:00
Object.defineProperty(this, 'codes', {
enumerable: false,
configurable: true,
value: {}
});
2011-10-10 13:22:51 +00:00
}
2013-04-04 15:31:07 +00:00
Errors.prototype.add = function (field, message, code) {
code = code || 'invalid';
2011-10-10 13:22:51 +00:00
if (!this[field]) {
2013-04-04 15:31:07 +00:00
this[field] = [];
this.codes[field] = [];
2011-10-10 13:22:51 +00:00
}
2013-04-04 15:31:07 +00:00
this[field].push(message);
this.codes[field].push(code);
};
function ErrorCodes(messages) {
var c = this;
Object.keys(messages).forEach(function(field) {
c[field] = messages[field].codes;
});
}
function ValidationError(obj) {
if (!(this instanceof ValidationError)) return new ValidationError(obj);
this.name = 'ValidationError';
this.message = 'Validation error';
this.statusCode = 400;
this.codes = obj.errors && obj.errors.codes;
2013-04-30 18:47:35 +00:00
this.context = obj && obj.constructor && obj.constructor.modelName;
2013-04-04 15:31:07 +00:00
Error.call(this);
Error.captureStackTrace(this, this.constructor);
}
2011-11-18 18:59:46 +00:00
util.inherits(ValidationError, Error);