UNPKG

ph-utils

Version:

js 开发工具集,前后端都可以使用(commonjs和es module)

72 lines (71 loc) 2.05 kB
/** * 数据验证器 */ interface RuleItem { rule: RegExp | ((v: any) => boolean) | "required"; message: string; sameKey?: string; } export type RuleType = string | RegExp | ((v: any) => boolean) | (RegExp | string | ((v: any) => boolean) | { rule: string | RegExp | ((v: any) => boolean); message?: string; }); export interface SchemaType { /** 数据字段 */ key: string; /** 是否必须 */ required?: boolean; /** 验证规则列表 */ rules?: RuleType[]; /** 错误信息 */ message?: string; } /** * 数据验证器 */ declare class Validator { rules: { [index: string]: RuleItem[]; }; /** * 构造数据验证转换器 * * See {@link https://gitee.com/towardly/ph/wikis/utils/validator|Validator文档}. * * @param schemas 配置验证转换规则 * * @example * * const validator = new Validator([ * { key: 'mobile', rules: ['required', 'mobile'] }, * { key: 'code': rules: /^\d{6}$/, message: '请输入正确的验证码' }, * { key: 'confirmPassword', rules: ['required', 'same:password'] } * ]) * // 验证某一个字段 * validator.validateKey().then(res => {}) */ constructor(schemas: SchemaType[]); addSchemas(schemas: SchemaType[]): void; addSchema(schema: SchemaType): void; /** * 进行数据验证 * @param data 待验证的数据 * @param all 是否全部验证, false - 只要验证错误一个则停止验证 * @returns */ validate(data: any, all?: boolean): Promise<boolean>; /** * 只验证指定 key 的数据格式 * @param key 指定待验证的 key * @param value 待验证的数据 * @param data 原始数据,当验证确认密码时需要使用 */ validateKey(key: string, value: any, data?: any): Promise<{ key: string; value: any; }>; private _validateRule; private _parseSchemaRules; private _parseStringRule; } export default Validator;