nope-validator
Version:
Fast and simple JS validator
107 lines (104 loc) • 3.61 kB
JavaScript
import { NopeReference } from './NopeReference.js';
import { isNil, runValidators, resolveNopeRefsFromKeys, resolveNopeRef } from './utils.js';
class NopePrimitive {
constructor() {
this.validationRules = [];
this._type = 'undefined';
}
getType() {
return this._type;
}
isEmpty(entry) {
return isNil(entry);
}
required(message = 'This field is required') {
const rule = (entry) => {
if (this.isEmpty(entry)) {
return message;
}
};
return this.test(rule);
}
notAllowed(message = 'Field is not allowed') {
const rule = (entry) => {
if (!this.isEmpty(entry)) {
return message;
}
};
return this.test(rule);
}
when(keys, conditionObject) {
const ctxKeys = Array.isArray(keys) ? keys : [keys];
const rule = (_, context) => {
const resolvedConditionValues = resolveNopeRefsFromKeys(ctxKeys, context);
const values = [...resolvedConditionValues];
const condIs = conditionObject.is;
const result = typeof condIs === 'function'
? condIs(...values)
: resolvedConditionValues.every((val) => val === condIs);
return result ? conditionObject.then : conditionObject.otherwise;
};
return this.test(rule);
}
oneOf(options, message = 'Invalid option') {
const rule = (entry, context) => {
if (entry === undefined) {
return;
}
let resolved;
if (options instanceof NopeReference) {
resolved = resolveNopeRef(options, context);
}
else {
resolved = options.map((option) => resolveNopeRef(option, context));
}
if (resolved.indexOf(entry) === -1) {
return message;
}
};
return this.test(rule);
}
notOneOf(options, message = 'Invalid Option') {
const rule = (entry, context) => {
const resolvedOptions = options.map((option) => resolveNopeRef(option, context));
if (resolvedOptions.indexOf(entry) !== -1) {
return message;
}
};
return this.test(rule);
}
test(rule) {
this.validationRules.push(rule);
return this;
}
/**
* @param entry - The value to be validated
* @param context - Used for internal reference resolving. Do not pass this.
*/
validate(entry, context) {
this._entry = entry;
for (const rule of this.validationRules) {
const error = rule(this._entry, context);
if (error instanceof NopePrimitive) {
return error.validate(this._entry, context);
}
else if (error) {
return error;
}
}
}
validateAsync(entry, context) {
var _a;
return runValidators(this.validationRules, (_a = this._entry) !== null && _a !== void 0 ? _a : entry, context).then((error) => {
var _a;
if (error instanceof NopePrimitive) {
return error.validateAsync((_a = this._entry) !== null && _a !== void 0 ? _a : entry, context);
}
else if (error) {
return error;
}
});
}
}
export { NopePrimitive };
//# sourceMappingURL=NopePrimitive.js.map