UNPKG

@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.

88 lines (87 loc) 2.49 kB
import { i18nUtils } from "@ticatec/i18n"; import i18nRes from "../i18nRes"; export default class BaseValidator { /** * 构建基础校验器 * @param field * @param options * @protected */ constructor(field, options) { var _a; this.field = field; this.required = typeof options.required == 'function' ? options.required : options.required == true; this.name = (_a = options.name) !== null && _a !== void 0 ? _a : field; this.checkFun = options.check; this.ignoreWhen = options.ignoreWhen; } validate(data, result, obj) { let ignore = this.ignoreWhen != null && this.ignoreWhen(obj); if (!ignore) { let value = this.extractFieldValue(data); if (this.checkNullValue(value)) { let required = typeof this.required == "function" ? this.required(data) : this.required; if (required) { result.setError(this.field, this.formatErrorMessage(i18nRes.validation.required, { field: this.name })); } } else { this.checkField(value, result, obj); } if (result.valid && this.checkFun != null) { let checkError = this.checkFun(value, obj); if (checkError != null) { result.setError(this.field, checkError); } } } } /** * 检查字段的值 * @param value * @param result * @param data * @protected */ checkField(value, result, data) { return true; } /** * 检查字段的类型并转换成对应的值 * @param value * @protected */ checkType(value) { return value; } /** * 获取字段的名称 * @protected */ getFieldLabel() { var _a; return (_a = this.name) !== null && _a !== void 0 ? _a : this.field; } /** * 检查是否为空 * @protected */ checkNullValue(value) { return value == null; } /** * 从数据中提前字段值 * @param data * @private */ extractFieldValue(data) { let value = data[this.field]; if (value != null) { value = this.checkType(value); } return value; } formatErrorMessage(message, params) { return params ? i18nUtils.formatText(message, params) : message; } }