ph-utils 0.2.23 → 0.3.1

Sign up to get free protection for your applications and to get access to all the features.
package/lib/validator.js CHANGED
@@ -1,215 +1,212 @@
1
- "use strict";
2
- /* eslint-disable @typescript-eslint/ban-ts-comment */
3
- /**
4
- * 数据验证器
5
- */
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- // 默认的错误提示信息
8
- const defaultMsgs = {
9
- mobile: '请输入正确的手机号',
10
- same: '两次输入不一致',
11
- required: '%s为必填字段',
12
- };
13
- const defaultMsg = '请输入正确的数据';
14
- // 一些常用的验证正则
15
- const ruleRegexs = {
16
- /** 验证跟其余数据相等的正则,一般用于验证再次输入密码 */
17
- same: /^same:(.+)$/i,
18
- /** 验证手机号的正则表达式 */
19
- mobile: /^1[34578]\d{9}$/,
20
- /** 非空验证的正则表达式 */
21
- required: /^\S{1}.*/,
22
- };
23
- // 规则比对函数
24
- const ruleFns = {
25
- /** 验证相等 */
26
- same(val1, val2) {
27
- return val2 === val1;
28
- },
29
- /** 正则匹配 */
30
- pattern(regex, val) {
31
- if (val == null) {
32
- return false;
33
- }
34
- return regex.test(String(val));
35
- },
36
- };
37
- class ValidateError extends Error {
38
- name;
39
- key;
40
- constructor(key, msg) {
41
- super(msg);
42
- this.name = 'ValidateError';
43
- this.key = key;
44
- }
45
- }
46
- /**
47
- * 数据验证器,除了进行数据验证外,还可以同时进行数据转化
48
- */
49
- class Validator {
50
- rules;
51
- /**
52
- * 构造数据验证转换器
53
- * @param schemas 配置验证转换规则
54
- */
55
- constructor(schemas) {
56
- let parsedRules = {};
57
- for (let schema of schemas) {
58
- // 解析规则
59
- let rules = [];
60
- let rule = schema.rules;
61
- if (typeof rule === 'string') {
62
- rules = rules.concat(this._parseStringRule(rule, schema.message));
63
- }
64
- else if (rule instanceof Array) {
65
- for (let ruleItem of rule) {
66
- if (typeof ruleItem === 'string') {
67
- rules.push(...this._parseStringRule(ruleItem, schema.message));
68
- }
69
- else if (ruleItem instanceof RegExp ||
70
- typeof ruleItem === 'function') {
71
- rules.push({
72
- rule: ruleItem,
73
- message: schema.message || defaultMsg,
74
- });
75
- }
76
- else {
77
- if (typeof ruleItem.rule === 'string') {
78
- rules.push(...this._parseStringRule(ruleItem.rule, ruleItem.message));
79
- }
80
- else {
81
- rules.push({
82
- rule: ruleItem.rule,
83
- message: ruleItem.message || defaultMsg,
84
- });
85
- }
86
- }
87
- }
88
- }
89
- else {
90
- rules.push({ rule, message: defaultMsg });
91
- }
92
- if (schema.required === true &&
93
- rules.findIndex((r) => r.rule === 'required') === -1) {
94
- rules.push(this._parseStringRule('required'));
95
- }
96
- parsedRules[schema.key] = rules;
97
- }
98
- this.rules = parsedRules;
99
- }
100
- /**
101
- * 进行数据验证
102
- * @param data 待验证的数据
103
- * @returns
104
- */
105
- validate(data) {
106
- return new Promise((resolve, reject) => {
107
- let errMsg = '';
108
- let errKey = '';
109
- for (let key in this.rules) {
110
- // eslint-disable-next-line no-prototype-builtins
111
- if (this.rules.hasOwnProperty(key)) {
112
- errMsg = this._validateRule(this.rules[key], data[key], data);
113
- if (errMsg !== '') {
114
- errKey = key;
115
- errMsg = errMsg.replace('%s', key);
116
- break;
117
- }
118
- }
119
- }
120
- if (errMsg === '') {
121
- resolve(true);
122
- }
123
- else {
124
- reject(new ValidateError(errKey, errMsg));
125
- }
126
- });
127
- }
128
- /**
129
- * 只验证指定 key 的数据格式
130
- * @param key 指定待验证的 key
131
- * @param value 待验证的数据
132
- */
133
- validateKey(key, value, data) {
134
- return new Promise((resolve, reject) => {
135
- let keyRules = this.rules[key];
136
- let errMsg = this._validateRule(keyRules, value, data);
137
- if (errMsg !== '') {
138
- errMsg = errMsg.replace('%s', key);
139
- reject(new ValidateError(key, errMsg));
140
- }
141
- else {
142
- resolve(true);
143
- }
144
- });
145
- }
146
- _validateRule(rules, value, data) {
147
- let errMsg = '';
148
- for (let rule of rules) {
149
- // 如果数据为空,则判断是否是必填
150
- if (rule.rule === 'required') {
151
- if (value == null || !ruleFns.pattern(ruleRegexs.required, value)) {
152
- errMsg = rule.message;
153
- }
154
- }
155
- if (typeof rule.rule === 'function') {
156
- if (!rule.rule(value)) {
157
- errMsg = rule.message;
158
- }
159
- }
160
- else if (rule.sameKey != null) {
161
- if (data != null) {
162
- if (!ruleFns.same(value, data[rule.sameKey])) {
163
- errMsg = rule.message;
164
- }
165
- }
166
- }
167
- else if (rule.rule === 'required') {
168
- if (!ruleFns.pattern(ruleRegexs.required, String(value))) {
169
- errMsg = rule.message;
170
- }
171
- }
172
- else {
173
- if (!ruleFns.pattern(rule.rule, String(value))) {
174
- errMsg = rule.message;
175
- }
176
- }
177
- if (errMsg !== '') {
178
- break;
179
- }
180
- }
181
- return errMsg;
182
- }
183
- _parseStringRule(rule, ruleErrMsg) {
184
- let rules = [];
185
- let trule = rule.split('|');
186
- for (let r of trule) {
187
- let message = ruleErrMsg;
188
- let rrule = null;
189
- let sameKey;
190
- if (ruleRegexs.same.test(r)) {
191
- let m = r.match(ruleRegexs.same);
192
- if (m != null) {
193
- rrule = ruleRegexs.same;
194
- let m = r.match(ruleRegexs.same);
195
- if (m != null) {
196
- sameKey = m[1];
197
- }
198
- message = message || defaultMsgs['same'];
199
- }
200
- }
201
- else if (rule === 'required') {
202
- rrule = 'required';
203
- message = message || ruleErrMsg || defaultMsgs.required;
204
- // eslint-disable-next-line no-prototype-builtins
205
- }
206
- else if (ruleRegexs.hasOwnProperty(r)) {
207
- rrule = ruleRegexs[r];
208
- message = message || defaultMsgs[r];
209
- }
210
- rules.push({ rule: rrule, message: message, sameKey });
211
- }
212
- return rules;
213
- }
214
- }
215
- exports.default = Validator;
1
+ /**
2
+ * 数据验证器
3
+ */
4
+ // 默认的错误提示信息
5
+ const defaultMsgs = {
6
+ mobile: '请输入正确的手机号',
7
+ same: '两次输入不一致',
8
+ required: '%s为必填字段',
9
+ };
10
+ const defaultMsg = '请输入正确的数据';
11
+ // 一些常用的验证正则
12
+ const ruleRegexs = {
13
+ /** 验证跟其余数据相等的正则,一般用于验证再次输入密码 */
14
+ same: /^same:(.+)$/i,
15
+ /** 验证手机号的正则表达式 */
16
+ mobile: /^1[34578]\d{9}$/,
17
+ /** 非空验证的正则表达式 */
18
+ required: /^\S{1}.*/,
19
+ };
20
+ // 规则比对函数
21
+ const ruleFns = {
22
+ /** 验证相等 */
23
+ same(val1, val2) {
24
+ return val2 === val1;
25
+ },
26
+ /** 正则匹配 */
27
+ pattern(regex, val) {
28
+ if (val == null) {
29
+ return false;
30
+ }
31
+ return regex.test(String(val));
32
+ },
33
+ };
34
+ class ValidateError extends Error {
35
+ name;
36
+ key;
37
+ constructor(key, msg) {
38
+ super(msg);
39
+ this.name = 'ValidateError';
40
+ this.key = key;
41
+ }
42
+ }
43
+ /**
44
+ * 数据验证器,除了进行数据验证外,还可以同时进行数据转化
45
+ */
46
+ class Validator {
47
+ rules;
48
+ /**
49
+ * 构造数据验证转换器
50
+ * @param schemas 配置验证转换规则
51
+ */
52
+ constructor(schemas) {
53
+ let parsedRules = {};
54
+ for (let schema of schemas) {
55
+ // 解析规则
56
+ let rules = [];
57
+ let rule = schema.rules;
58
+ if (rule != null) {
59
+ if (typeof rule === 'string') {
60
+ rules = rules.concat(this._parseStringRule(rule, schema.message));
61
+ }
62
+ else if (rule instanceof Array) {
63
+ for (let ruleItem of rule) {
64
+ if (typeof ruleItem === 'string') {
65
+ rules.push(...this._parseStringRule(ruleItem, schema.message));
66
+ }
67
+ else if (ruleItem instanceof RegExp || typeof ruleItem === 'function') {
68
+ rules.push({
69
+ rule: ruleItem,
70
+ message: schema.message || defaultMsg,
71
+ });
72
+ }
73
+ else {
74
+ if (typeof ruleItem.rule === 'string') {
75
+ rules.push(...this._parseStringRule(ruleItem.rule, ruleItem.message));
76
+ }
77
+ else {
78
+ rules.push({
79
+ rule: ruleItem.rule,
80
+ message: ruleItem.message || defaultMsg,
81
+ });
82
+ }
83
+ }
84
+ }
85
+ }
86
+ else {
87
+ rules.push({ rule, message: defaultMsg });
88
+ }
89
+ }
90
+ if (schema.required === true && (rules == null || rules.findIndex((r) => r.rule === 'required') === -1)) {
91
+ rules.push(...this._parseStringRule('required', schema.message));
92
+ }
93
+ parsedRules[schema.key] = rules;
94
+ }
95
+ this.rules = parsedRules;
96
+ }
97
+ /**
98
+ * 进行数据验证
99
+ * @param data 待验证的数据
100
+ * @returns
101
+ */
102
+ validate(data) {
103
+ return new Promise((resolve, reject) => {
104
+ let errMsg = '';
105
+ let errKey = '';
106
+ for (let key in this.rules) {
107
+ // eslint-disable-next-line no-prototype-builtins
108
+ if (this.rules.hasOwnProperty(key)) {
109
+ errMsg = this._validateRule(this.rules[key], data[key], data);
110
+ if (errMsg !== '') {
111
+ errKey = key;
112
+ errMsg = errMsg.replace('%s', key);
113
+ break;
114
+ }
115
+ }
116
+ }
117
+ if (errMsg === '') {
118
+ resolve(true);
119
+ }
120
+ else {
121
+ reject(new ValidateError(errKey, errMsg));
122
+ }
123
+ });
124
+ }
125
+ /**
126
+ * 只验证指定 key 的数据格式
127
+ * @param key 指定待验证的 key
128
+ * @param value 待验证的数据
129
+ */
130
+ validateKey(key, value, data) {
131
+ return new Promise((resolve, reject) => {
132
+ let keyRules = this.rules[key];
133
+ let errMsg = this._validateRule(keyRules, value, data);
134
+ if (errMsg !== '') {
135
+ errMsg = errMsg.replace('%s', key);
136
+ reject(new ValidateError(key, errMsg));
137
+ }
138
+ else {
139
+ resolve(true);
140
+ }
141
+ });
142
+ }
143
+ _validateRule(rules, value, data) {
144
+ let errMsg = '';
145
+ for (let rule of rules) {
146
+ // 如果数据为空,则判断是否是必填
147
+ if (rule.rule === 'required') {
148
+ if (value == null || !ruleFns.pattern(ruleRegexs.required, value)) {
149
+ errMsg = rule.message;
150
+ }
151
+ }
152
+ if (typeof rule.rule === 'function') {
153
+ if (!rule.rule(value)) {
154
+ errMsg = rule.message;
155
+ }
156
+ }
157
+ else if (rule.sameKey != null) {
158
+ if (data != null) {
159
+ if (!ruleFns.same(value, data[rule.sameKey])) {
160
+ errMsg = rule.message;
161
+ }
162
+ }
163
+ }
164
+ else if (rule.rule === 'required') {
165
+ if (!ruleFns.pattern(ruleRegexs.required, String(value))) {
166
+ errMsg = rule.message;
167
+ }
168
+ }
169
+ else {
170
+ if (!ruleFns.pattern(rule.rule, String(value))) {
171
+ errMsg = rule.message;
172
+ }
173
+ }
174
+ if (errMsg !== '') {
175
+ break;
176
+ }
177
+ }
178
+ return errMsg;
179
+ }
180
+ _parseStringRule(rule, ruleErrMsg) {
181
+ let rules = [];
182
+ let trule = rule.split('|');
183
+ for (let r of trule) {
184
+ let message = ruleErrMsg;
185
+ let rrule = null;
186
+ let sameKey;
187
+ if (ruleRegexs.same.test(r)) {
188
+ let m = r.match(ruleRegexs.same);
189
+ if (m != null) {
190
+ rrule = ruleRegexs.same;
191
+ let m = r.match(ruleRegexs.same);
192
+ if (m != null) {
193
+ sameKey = m[1];
194
+ }
195
+ message = message || defaultMsgs['same'];
196
+ }
197
+ }
198
+ else if (rule === 'required') {
199
+ rrule = 'required';
200
+ message = message || ruleErrMsg || defaultMsgs.required;
201
+ // eslint-disable-next-line no-prototype-builtins
202
+ }
203
+ else if (ruleRegexs.hasOwnProperty(r)) {
204
+ rrule = ruleRegexs[r];
205
+ message = message || defaultMsgs[r];
206
+ }
207
+ rules.push({ rule: rrule, message: message, sameKey });
208
+ }
209
+ return rules;
210
+ }
211
+ }
212
+ export default Validator;
package/lib/web.d.ts CHANGED
@@ -1,55 +1,13 @@
1
- /**
2
- * 解析 Form 表单中的 input 元素的数据为 JSON 格式,key: input-name;value: input-value
3
- * @param form {object} Form 节点对象
4
- */
5
- export declare const formJson: <T>(form: HTMLFormElement) => T;
6
- /**
7
- * 获取 url query 参数 (get 请求的参数)
8
- * @param search 如果是 React 应用就需要传递 useLocation().search
9
- * @returns
10
- */
11
- export declare function query(search?: string): {
12
- [index: string]: string;
13
- };
14
- interface RandomOpts {
15
- /** 生成的随机数是整形还是小数形 */
16
- isInt?: boolean;
17
- /** 生成的随机数是否包含末尾数字 end, 仅在有 end 参数并且 isInt = true 时有效; true 表示包含 */
18
- hasEnd?: boolean;
19
- }
20
- /**
21
- * 生成指定长度的随机数
22
- * @param len 生成的随机数长度
23
- * @param firstZero 生成的随机数第一位是否可以包含 0,默认为 true
24
- */
25
- export declare function random(len: number, firstZero?: boolean): string;
26
- /**
27
- * 生成介于 min 和 max 之间的随机数
28
- * @param min 最小值
29
- * @param max 最大值
30
- * @param opts 配置项
31
- * @property opts.isInt 生成的随机数是整形还是小数形
32
- * @property opts.hasEnd 生成的随机数是否包含末尾数字 max, 仅在有 max 参数并且 isInt = true 时有效; true 表示包含
33
- */
34
- export declare function random(min: number, max: number, opts?: RandomOpts): number;
35
- /**
36
- * 将金额数字格式化为金额格式显示并且会保留两位小数[去除多余的位数,不是四舍五入,而是直接舍去] 1234523432.23 => 123,123,123.23
37
- * @param {number} number 待转换的金额数字
38
- * @return string
39
- */
40
- export declare function formatMoney(number: number): string;
41
- /**
42
- * 函数节流 - 每隔单位时间,只执行一次
43
- * @param cb 待节流的函数
44
- * @param wait 间隔时间
45
- * @returns
46
- */
47
- export declare function throttle<R extends any[], T>(fn: (...args: R) => T, wait?: number): (...args: R) => void;
48
- /**
49
- * 函数防抖 - 当重复触发某一个行为(事件时),只执行最后一次触发
50
- * @param fn 防抖函数
51
- * @param interval 间隔时间段
52
- * @returns
53
- */
54
- export declare function debounce<R extends any[], T>(fn: (...args: R) => T, interval?: number): (...args: R) => void;
55
- export {};
1
+ /**
2
+ * 解析 Form 表单中的 input 元素的数据为 JSON 格式,key: input-name;value: input-value
3
+ * @param form {object} Form 节点对象
4
+ */
5
+ export declare const formJson: <T>(form: HTMLFormElement) => T;
6
+ /**
7
+ * 获取 url query 参数 (get 请求的参数)
8
+ * @param search 如果是 React 应用就需要传递 useLocation().search
9
+ * @returns
10
+ */
11
+ export declare function query(search?: string): {
12
+ [index: string]: string;
13
+ };