@ticatec/web-bean-validator
Version:
A TypeScript/JavaScript library for rule-based entity validation with boundary checking for strings, numbers, dates, enums, objects, and arrays.
42 lines (41 loc) • 1.59 kB
JavaScript
import NestValidator from "./NestValidator";
import i18nRes from "../i18nRes";
export default class ArrayValidator extends NestValidator {
constructor(field, options) {
super(field, options);
this.rules = options === null || options === void 0 ? void 0 : options.rules;
this.minLen = options === null || options === void 0 ? void 0 : options.minLen;
this.maxLen = options === null || options === void 0 ? void 0 : options.maxLen;
}
checkField(arr, result, data) {
if (this.minLen != null && arr.length < this.minLen) {
result.setError(this.field, this.formatErrorMessage(i18nRes.validation.arrayShortage, {
field: this.name,
length: this.minLen
}));
return false;
}
else if (this.maxLen != null && arr.length > this.maxLen) {
result.setError(this.field, this.formatErrorMessage(i18nRes.validation.arrayExceed, {
field: this.name,
length: this.maxLen
}));
return false;
}
if (this.rules && arr.length > 0) {
let valid = true;
let errList = [];
arr.forEach((item, idx) => {
let vr = this.validateObj(item, this.rules, data);
valid = valid && vr.valid;
errList.push(vr.errors);
});
if (!valid) {
result.setError(this.field, errList);
}
}
}
checkType(value) {
return Array.isArray(value) ? value : null;
}
}