validator.js-asserts
Version:
A set of extra asserts for validator.js.
57 lines (41 loc) • 990 B
JavaScript
'use strict';
/**
* Module dependencies.
*/
const { Assert: is, Violation } = require('validator.js');
/**
* Export `NullOrStringAssert`.
*/
module.exports = function nullOrStringAssert(boundaries) {
/**
* Class name.
*/
this.__class__ = 'NullOrString';
/**
* Boundaries.
*/
boundaries = boundaries || {};
this.min = boundaries.min;
this.max = boundaries.max;
/**
* Validation algorithm.
*/
this.validate = value => {
if (value !== null && typeof value !== 'string') {
throw new Violation(this, value, { value: 'must_be_null_or_a_string' });
}
if (value === null) {
return true;
}
if (typeof value === 'string' && typeof this.min === 'undefined' && typeof this.max === 'undefined') {
return true;
}
try {
is.ofLength({ max: this.max, min: this.min }).validate(value);
} catch (e) {
throw new Violation(this, value, e.violation);
}
return true;
};
return this;
};