@10yun/cv-mobile-ui 0.4.4 → 0.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@10yun/cv-mobile-ui",
3
- "version": "0.4.4",
3
+ "version": "0.4.6",
4
4
  "description": "十云cvjs移动端ui,适用uniapp",
5
5
  "author": "",
6
6
  "license": "Apache-2.0",
@@ -1,32 +1,6 @@
1
1
  <template>
2
2
  <view class="cv-button-wrap">
3
- <button v-if="type == 'pay'" class="cv-button-item cv-button-pay" type="primary" @click="parentClick">{{ label }}</button>
4
- <button v-else-if="type == 'save'" class="cv-button-item cv-button-save" type="error" @click="parentClick">
5
- {{ label }}
6
- </button>
7
- <button
8
- v-else-if="type == 'submit'"
9
- class="cv-button-item cv-button-save"
10
- type="primary"
11
- form-type="submit"
12
- @click="parentClick"
13
- >
14
- {{ label }}
15
- </button>
16
- <button
17
- v-else-if="type == 'reset'"
18
- class="cv-button-item cv-button-cancel"
19
- type="primary"
20
- form-type="reset"
21
- @click="parentClick"
22
- >
23
- {{ label }}
24
- </button>
25
- <button v-else-if="type == 'cancel'" class="cv-button-item cv-button-cancel" type="primary" @click="parentClick">
26
- {{ label }}
27
- </button>
28
- <button v-else class="cv-button-item" type="primary" @click="parentClick">{{ label }}</button>
29
- <!-- :style="{ background: themesData.color }" -->
3
+ <button class="cv-button-item" :type="type" :form-type="formType" @click="parentClick"><slot /></button>
30
4
  </view>
31
5
  </template>
32
6
 
@@ -35,15 +9,19 @@ export default {
35
9
  name: 'cvButton',
36
10
  props: {
37
11
  label: {
38
- type: String,
39
- default: 'save'
12
+ type: [String],
13
+ default: 'primary'
40
14
  },
41
15
  type: {
42
- type: String,
16
+ type: [String],
43
17
  default: 'save'
44
18
  },
19
+ formType: {
20
+ type: [String],
21
+ default: ''
22
+ },
45
23
  click: {
46
- type: Function
24
+ type: [Function]
47
25
  }
48
26
  },
49
27
  data() {
@@ -84,23 +62,12 @@ export default {
84
62
  border-radius: 40px;
85
63
  }
86
64
 
87
- .cv-button-pay {
65
+ .cv-button-item2 {
88
66
  display: flex;
89
67
  justify-content: center;
90
68
  align-items: center;
91
69
  width: 275px;
92
70
  height: 40px;
93
- background-color: #62a9df;
94
- box-shadow: 0rpx 5rpx 10rpx rgba(0, 0, 0, 0.2);
95
71
  margin: 10px auto;
96
72
  }
97
- .cv-button-save {
98
- background: #e4393c;
99
- background: linear-gradient(to right, #ffa300, #ff8a00, #e95f00);
100
- }
101
- .cv-button-cancel {
102
- background-color: #fff;
103
- border: 1px solid #d4d4d4;
104
- color: #202020;
105
- }
106
73
  </style>
@@ -0,0 +1,470 @@
1
+ <template>
2
+ <view class="uni-forms" :class="{ 'uni-forms--top': !border }">
3
+ <form @submit.stop="submitForm" @reset="resetForm">
4
+ <slot></slot>
5
+ </form>
6
+ </view>
7
+ </template>
8
+
9
+ <script>
10
+ // #ifndef VUE3
11
+ import Vue from 'vue';
12
+ Vue.prototype.binddata = function (name, value, formName) {
13
+ if (formName) {
14
+ this.$refs[formName].setValue(name, value);
15
+ } else {
16
+ let formVm;
17
+ for (let i in this.$refs) {
18
+ const vm = this.$refs[i];
19
+ if (vm && vm.$options && vm.$options.name === 'uniForms') {
20
+ formVm = vm;
21
+ break;
22
+ }
23
+ }
24
+ if (!formVm) return console.error('当前 uni-froms 组件缺少 ref 属性');
25
+ formVm.setValue(name, value);
26
+ }
27
+ };
28
+ // #endif
29
+
30
+ import Validator from './validate.js';
31
+ /**
32
+ * Forms 表单
33
+ * @description 由输入框、选择器、单选框、多选框等控件组成,用以收集、校验、提交数据
34
+ * @tutorial https://ext.dcloud.net.cn/plugin?id=2773
35
+ * @property {Object} rules 表单校验规则
36
+ * @property {String} validateTrigger = [bind|submit] 校验触发器方式 默认 submit
37
+ * @value bind 发生变化时触发
38
+ * @value submit 提交时触发
39
+ * @property {String} labelPosition = [top|left] label 位置 默认 left
40
+ * @value top 顶部显示 label
41
+ * @value left 左侧显示 label
42
+ * @property {String} labelWidth label 宽度,默认 65px
43
+ * @property {String} labelAlign = [left|center|right] label 居中方式 默认 left
44
+ * @value left label 左侧显示
45
+ * @value center label 居中
46
+ * @value right label 右侧对齐
47
+ * @property {String} errShowType = [undertext|toast|modal] 校验错误信息提示方式
48
+ * @value undertext 错误信息在底部显示
49
+ * @value toast 错误信息toast显示
50
+ * @value modal 错误信息modal显示
51
+ * @event {Function} submit 提交时触发
52
+ */
53
+
54
+ export default {
55
+ name: 'cvFormBase',
56
+ components: {},
57
+ model: {
58
+ prop: 'modelValue',
59
+ event: 'update:modelValue'
60
+ },
61
+ emits: ['update:modelValue', 'input', 'reset', 'validate', 'submit'],
62
+ props: {
63
+ // 即将弃用
64
+ value: {
65
+ type: Object,
66
+ default() {
67
+ return {};
68
+ }
69
+ },
70
+ // 替换 value 属性
71
+ modelValue: {
72
+ type: Object,
73
+ default() {
74
+ return {};
75
+ }
76
+ },
77
+ // 表单校验规则
78
+ rules: {
79
+ type: Object,
80
+ default() {
81
+ return {};
82
+ }
83
+ },
84
+ // 校验触发器方式,默认 关闭
85
+ validateTrigger: {
86
+ type: String,
87
+ default: ''
88
+ },
89
+ // label 位置,可选值 top/left
90
+ labelPosition: {
91
+ type: String,
92
+ default: 'left'
93
+ },
94
+ // label 宽度,单位 px
95
+ labelWidth: {
96
+ type: [String, Number],
97
+ default: ''
98
+ },
99
+ // label 居中方式,可选值 left/center/right
100
+ labelAlign: {
101
+ type: String,
102
+ default: 'left'
103
+ },
104
+ errShowType: {
105
+ type: String,
106
+ default: 'undertext'
107
+ },
108
+ border: {
109
+ type: Boolean,
110
+ default: false
111
+ },
112
+ line: {
113
+ type: Boolean,
114
+ default: true
115
+ }
116
+ },
117
+ data() {
118
+ return {
119
+ formData: {}
120
+ };
121
+ },
122
+ computed: {
123
+ dataValue() {
124
+ if (JSON.stringify(this.modelValue) === '{}') {
125
+ return this.value;
126
+ } else {
127
+ return this.modelValue;
128
+ }
129
+ }
130
+ },
131
+ watch: {
132
+ rules(newVal) {
133
+ // 如果规则发生变化,要初始化组件
134
+ this.init(newVal);
135
+ },
136
+ labelPosition() {
137
+ this.childrens.forEach((vm) => {
138
+ vm.init();
139
+ });
140
+ }
141
+ },
142
+ created() {
143
+ // #ifdef VUE3
144
+ let getbinddata = getApp().$vm.$.appContext.config.globalProperties.binddata;
145
+ if (!getbinddata) {
146
+ getApp().$vm.$.appContext.config.globalProperties.binddata = function (name, value, formName) {
147
+ if (formName) {
148
+ this.$refs[formName].setValue(name, value);
149
+ } else {
150
+ let formVm;
151
+ for (let i in this.$refs) {
152
+ const vm = this.$refs[i];
153
+ if (vm && vm.$options && vm.$options.name === 'uniForms') {
154
+ formVm = vm;
155
+ break;
156
+ }
157
+ }
158
+ if (!formVm) return console.error('当前 uni-froms 组件缺少 ref 属性');
159
+ formVm.setValue(name, value);
160
+ }
161
+ };
162
+ }
163
+ // #endif
164
+
165
+ // 存放watch 监听数组
166
+ this.unwatchs = [];
167
+ // 存放子组件数组
168
+ this.childrens = [];
169
+ // 存放 easyInput 组件
170
+ this.inputChildrens = [];
171
+ // 存放 dataCheckbox 组件
172
+ this.checkboxChildrens = [];
173
+ // 存放规则
174
+ this.formRules = [];
175
+ this.init(this.rules);
176
+ },
177
+ // mounted() {
178
+ // this.init(this.rules)
179
+ // },
180
+ methods: {
181
+ init(formRules) {
182
+ // 判断是否有规则
183
+ if (Object.keys(formRules).length === 0) {
184
+ this.formData = this.dataValue;
185
+ return;
186
+ }
187
+ this.formRules = formRules;
188
+ this.validator = new Validator(formRules);
189
+ this.registerWatch();
190
+ },
191
+ // 监听 watch
192
+ registerWatch() {
193
+ // 取消监听,避免多次调用 init 重复执行 $watch
194
+ this.unwatchs.forEach((v) => v());
195
+ this.childrens.forEach((v) => {
196
+ v.init();
197
+ });
198
+ // watch 每个属性 ,需要知道具体那个属性发变化
199
+ Object.keys(this.dataValue).forEach((key) => {
200
+ let watch = this.$watch(
201
+ 'dataValue.' + key,
202
+ (value) => {
203
+ if (!value) return;
204
+ // 如果是对象 ,则平铺内容
205
+ if (value.toString() === '[object Object]') {
206
+ for (let i in value) {
207
+ let name = `${key}[${i}]`;
208
+ this.formData[name] = this._getValue(name, value[i]);
209
+ }
210
+ } else {
211
+ this.formData[key] = this._getValue(key, value);
212
+ }
213
+ },
214
+ {
215
+ deep: true,
216
+ immediate: true
217
+ }
218
+ );
219
+ this.unwatchs.push(watch);
220
+ });
221
+ },
222
+ /**
223
+ * 公开给用户使用
224
+ * 设置校验规则
225
+ * @param {Object} formRules
226
+ */
227
+ setRules(formRules) {
228
+ this.init(formRules);
229
+ },
230
+ /**
231
+ * 公开给用户使用
232
+ * 设置自定义表单组件 value 值
233
+ * @param {String} name 字段名称
234
+ * @param {String} value 字段值
235
+ */
236
+ setValue(name, value, callback) {
237
+ let example = this.childrens.find((child) => child.name === name);
238
+ if (!example) return null;
239
+ value = this._getValue(example.name, value);
240
+ this.formData[name] = value;
241
+ example.val = value;
242
+ this.$emit('input', Object.assign({}, this.value, this.formData));
243
+ this.$emit('update:modelValue', Object.assign({}, this.value, this.formData));
244
+ return example.triggerCheck(value, callback);
245
+ },
246
+
247
+ /**
248
+ * 表单重置
249
+ * @param {Object} event
250
+ */
251
+ resetForm(event) {
252
+ this.childrens.forEach((item) => {
253
+ item.errMsg = '';
254
+ const inputComp = this.inputChildrens.find((child) => child.rename === item.name);
255
+ if (inputComp) {
256
+ inputComp.errMsg = '';
257
+ inputComp.$emit('input', inputComp.multiple ? [] : '');
258
+ inputComp.$emit('update:modelValue', inputComp.multiple ? [] : '');
259
+ }
260
+ });
261
+
262
+ this.childrens.forEach((item) => {
263
+ if (item.name) {
264
+ this.formData[item.name] = this._getValue(item.name, '');
265
+ }
266
+ });
267
+
268
+ this.$emit('input', this.formData);
269
+ this.$emit('update:modelValue', this.formData);
270
+ this.$emit('reset', event);
271
+ },
272
+
273
+ /**
274
+ * 触发表单校验,通过 @validate 获取
275
+ * @param {Object} validate
276
+ */
277
+ validateCheck(validate) {
278
+ if (validate === null) validate = null;
279
+ this.$emit('validate', validate);
280
+ },
281
+ /**
282
+ * 校验所有或者部分表单
283
+ */
284
+ async validateAll(invalidFields, type, keepitem, callback) {
285
+ let childrens = [];
286
+ for (let i in invalidFields) {
287
+ const item = this.childrens.find((v) => v.name === i);
288
+ if (item) {
289
+ childrens.push(item);
290
+ }
291
+ }
292
+
293
+ if (!callback && typeof keepitem === 'function') {
294
+ callback = keepitem;
295
+ }
296
+
297
+ let promise;
298
+ if (!callback && typeof callback !== 'function' && Promise) {
299
+ promise = new Promise((resolve, reject) => {
300
+ callback = function (valid, invalidFields) {
301
+ !valid ? resolve(invalidFields) : reject(valid);
302
+ };
303
+ });
304
+ }
305
+
306
+ let results = [];
307
+ let newFormData = {};
308
+ if (this.validator) {
309
+ for (let key in childrens) {
310
+ const child = childrens[key];
311
+ let name = child.isArray ? child.arrayField : child.name;
312
+ if (child.isArray) {
313
+ if (child.name.indexOf('[') !== -1 && child.name.indexOf(']') !== -1) {
314
+ const fieldData = child.name.split('[');
315
+ const fieldName = fieldData[0];
316
+ const fieldValue = fieldData[1].replace(']', '');
317
+ if (!newFormData[fieldName]) {
318
+ newFormData[fieldName] = {};
319
+ }
320
+ newFormData[fieldName][fieldValue] = this._getValue(name, invalidFields[name]);
321
+ }
322
+ } else {
323
+ newFormData[name] = this._getValue(name, invalidFields[name]);
324
+ }
325
+ const result = await child.triggerCheck(invalidFields[name], true);
326
+ if (result) {
327
+ results.push(result);
328
+ if (this.errShowType === 'toast' || this.errShowType === 'modal') break;
329
+ }
330
+ }
331
+ } else {
332
+ newFormData = invalidFields;
333
+ }
334
+ if (Array.isArray(results)) {
335
+ if (results.length === 0) results = null;
336
+ }
337
+
338
+ if (Array.isArray(keepitem)) {
339
+ keepitem.forEach((v) => {
340
+ newFormData[v] = this.dataValue[v];
341
+ });
342
+ }
343
+
344
+ if (type === 'submit') {
345
+ this.$emit('submit', {
346
+ detail: {
347
+ value: newFormData,
348
+ errors: results
349
+ }
350
+ });
351
+ } else {
352
+ this.$emit('validate', results);
353
+ }
354
+
355
+ callback && typeof callback === 'function' && callback(results, newFormData);
356
+
357
+ if (promise && callback) {
358
+ return promise;
359
+ } else {
360
+ return null;
361
+ }
362
+ },
363
+ submitForm() {},
364
+ /**
365
+ * 外部调用方法
366
+ * 手动提交校验表单
367
+ * 对整个表单进行校验的方法,参数为一个回调函数。
368
+ */
369
+ submit(keepitem, callback, type) {
370
+ for (let i in this.dataValue) {
371
+ const itemData = this.childrens.find((v) => v.name === i);
372
+ if (itemData) {
373
+ if (this.formData[i] === undefined) {
374
+ this.formData[i] = this._getValue(i, this.dataValue[i]);
375
+ }
376
+ }
377
+ }
378
+ if (!type) {
379
+ console.warn('submit 方法即将废弃,请使用validate方法代替!');
380
+ }
381
+ return this.validateAll(this.formData, 'submit', keepitem, callback);
382
+ },
383
+
384
+ /**
385
+ * 外部调用方法
386
+ * 校验表单
387
+ * 对整个表单进行校验的方法,参数为一个回调函数。
388
+ */
389
+ validate(keepitem, callback) {
390
+ return this.submit(keepitem, callback, true);
391
+ },
392
+
393
+ /**
394
+ * 部分表单校验
395
+ * @param {Object} props
396
+ * @param {Object} cb
397
+ */
398
+ validateField(props, callback) {
399
+ props = [].concat(props);
400
+ let invalidFields = {};
401
+ this.childrens.forEach((item) => {
402
+ if (props.indexOf(item.name) !== -1) {
403
+ invalidFields = Object.assign({}, invalidFields, {
404
+ [item.name]: this.formData[item.name]
405
+ });
406
+ }
407
+ });
408
+ return this.validateAll(invalidFields, 'submit', [], callback);
409
+ },
410
+
411
+ /**
412
+ * 对整个表单进行重置,将所有字段值重置为初始值并移除校验结果
413
+ */
414
+ resetFields() {
415
+ this.resetForm();
416
+ },
417
+
418
+ /**
419
+ * 移除表单项的校验结果。传入待移除的表单项的 prop 属性或者 prop 组成的数组,如不传则移除整个表单的校验结果
420
+ */
421
+ clearValidate(props) {
422
+ props = [].concat(props);
423
+ this.childrens.forEach((item) => {
424
+ const inputComp = this.inputChildrens.find((child) => child.rename === item.name);
425
+ if (props.length === 0) {
426
+ item.errMsg = '';
427
+ if (inputComp) {
428
+ inputComp.errMsg = '';
429
+ }
430
+ } else {
431
+ if (props.indexOf(item.name) !== -1) {
432
+ item.errMsg = '';
433
+ if (inputComp) {
434
+ inputComp.errMsg = '';
435
+ }
436
+ }
437
+ }
438
+ });
439
+ },
440
+ /**
441
+ * 把 value 转换成指定的类型
442
+ * @param {Object} key
443
+ * @param {Object} value
444
+ */
445
+ _getValue(key, value) {
446
+ const rules = (this.formRules[key] && this.formRules[key].rules) || [];
447
+ const isRuleNum = rules.find((val) => val.format && this.type_filter(val.format));
448
+ const isRuleBool = rules.find((val) => (val.format && val.format === 'boolean') || val.format === 'bool');
449
+ // 输入值为 number
450
+ if (isRuleNum) {
451
+ value = isNaN(value) ? value : value === '' || value === null ? null : Number(value);
452
+ }
453
+ // 简单判断真假值
454
+ if (isRuleBool) {
455
+ value = !value ? false : true;
456
+ }
457
+ return value;
458
+ },
459
+ /**
460
+ * 过滤数字类型
461
+ * @param {Object} format
462
+ */
463
+ type_filter(format) {
464
+ return format === 'int' || format === 'double' || format === 'number' || format === 'timestamp';
465
+ }
466
+ }
467
+ };
468
+ </script>
469
+
470
+ <style scoped></style>
@@ -0,0 +1,477 @@
1
+ var pattern = {
2
+ email: /^\S+?@\S+?\.\S+?$/,
3
+ idcard: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
4
+ url: new RegExp(
5
+ '^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$',
6
+ 'i'
7
+ )
8
+ };
9
+
10
+ const FORMAT_MAPPING = {
11
+ int: 'integer',
12
+ bool: 'boolean',
13
+ double: 'number',
14
+ long: 'number',
15
+ password: 'string'
16
+ // "fileurls": 'array'
17
+ };
18
+
19
+ function formatMessage(args, resources = '') {
20
+ var defaultMessage = ['label'];
21
+ defaultMessage.forEach((item) => {
22
+ if (args[item] === undefined) {
23
+ args[item] = '';
24
+ }
25
+ });
26
+
27
+ let str = resources;
28
+ for (let key in args) {
29
+ let reg = new RegExp('{' + key + '}');
30
+ str = str.replace(reg, args[key]);
31
+ }
32
+ return str;
33
+ }
34
+
35
+ function isEmptyValue(value, type) {
36
+ if (value === undefined || value === null) {
37
+ return true;
38
+ }
39
+
40
+ if (typeof value === 'string' && !value) {
41
+ return true;
42
+ }
43
+
44
+ if (Array.isArray(value) && !value.length) {
45
+ return true;
46
+ }
47
+
48
+ if (type === 'object' && !Object.keys(value).length) {
49
+ return true;
50
+ }
51
+
52
+ return false;
53
+ }
54
+
55
+ const types = {
56
+ integer(value) {
57
+ return types.number(value) && parseInt(value, 10) === value;
58
+ },
59
+ string(value) {
60
+ return typeof value === 'string';
61
+ },
62
+ number(value) {
63
+ if (isNaN(value)) {
64
+ return false;
65
+ }
66
+ return typeof value === 'number';
67
+ },
68
+ boolean: function (value) {
69
+ return typeof value === 'boolean';
70
+ },
71
+ float: function (value) {
72
+ return types.number(value) && !types.integer(value);
73
+ },
74
+ array(value) {
75
+ return Array.isArray(value);
76
+ },
77
+ object(value) {
78
+ return typeof value === 'object' && !types.array(value);
79
+ },
80
+ date(value) {
81
+ return value instanceof Date;
82
+ },
83
+ timestamp(value) {
84
+ if (!this.integer(value) || Math.abs(value).toString().length > 16) {
85
+ return false;
86
+ }
87
+ return true;
88
+ },
89
+ file(value) {
90
+ return typeof value.url === 'string';
91
+ },
92
+ email(value) {
93
+ return typeof value === 'string' && !!value.match(pattern.email) && value.length < 255;
94
+ },
95
+ url(value) {
96
+ return typeof value === 'string' && !!value.match(pattern.url);
97
+ },
98
+ pattern(reg, value) {
99
+ try {
100
+ return new RegExp(reg).test(value);
101
+ } catch (e) {
102
+ return false;
103
+ }
104
+ },
105
+ method(value) {
106
+ return typeof value === 'function';
107
+ },
108
+ idcard(value) {
109
+ return typeof value === 'string' && !!value.match(pattern.idcard);
110
+ },
111
+ 'url-https'(value) {
112
+ return this.url(value) && value.startsWith('https://');
113
+ },
114
+ 'url-scheme'(value) {
115
+ return value.startsWith('://');
116
+ },
117
+ 'url-web'(value) {
118
+ return false;
119
+ }
120
+ };
121
+
122
+ class RuleValidator {
123
+ constructor(message) {
124
+ this._message = message;
125
+ }
126
+
127
+ async validateRule(fieldKey, fieldValue, value, data, allData) {
128
+ var result = null;
129
+
130
+ let rules = fieldValue.rules;
131
+
132
+ let hasRequired = rules.findIndex((item) => {
133
+ return item.required;
134
+ });
135
+ if (hasRequired < 0) {
136
+ if (value === null || value === undefined) {
137
+ return result;
138
+ }
139
+ if (typeof value === 'string' && !value.length) {
140
+ return result;
141
+ }
142
+ }
143
+
144
+ var message = this._message;
145
+
146
+ if (rules === undefined) {
147
+ return message['default'];
148
+ }
149
+
150
+ for (var i = 0; i < rules.length; i++) {
151
+ let rule = rules[i];
152
+ let vt = this._getValidateType(rule);
153
+
154
+ Object.assign(rule, {
155
+ label: fieldValue.label || `["${fieldKey}"]`
156
+ });
157
+
158
+ if (RuleValidatorHelper[vt]) {
159
+ result = RuleValidatorHelper[vt](rule, value, message);
160
+ if (result != null) {
161
+ break;
162
+ }
163
+ }
164
+
165
+ if (rule.validateExpr) {
166
+ let now = Date.now();
167
+ let resultExpr = rule.validateExpr(value, allData, now);
168
+ if (resultExpr === false) {
169
+ result = this._getMessage(rule, rule.errorMessage || this._message['default']);
170
+ break;
171
+ }
172
+ }
173
+
174
+ if (rule.validateFunction) {
175
+ result = await this.validateFunction(rule, value, data, allData, vt);
176
+ if (result !== null) {
177
+ break;
178
+ }
179
+ }
180
+ }
181
+
182
+ if (result !== null) {
183
+ result = message.TAG + result;
184
+ }
185
+
186
+ return result;
187
+ }
188
+
189
+ async validateFunction(rule, value, data, allData, vt) {
190
+ let result = null;
191
+ try {
192
+ let callbackMessage = null;
193
+ const res = await rule.validateFunction(rule, value, allData || data, (message) => {
194
+ callbackMessage = message;
195
+ });
196
+ if (callbackMessage || (typeof res === 'string' && res) || res === false) {
197
+ result = this._getMessage(rule, callbackMessage || res, vt);
198
+ }
199
+ } catch (e) {
200
+ result = this._getMessage(rule, e.message, vt);
201
+ }
202
+ return result;
203
+ }
204
+
205
+ _getMessage(rule, message, vt) {
206
+ return formatMessage(rule, message || rule.errorMessage || this._message[vt] || message['default']);
207
+ }
208
+
209
+ _getValidateType(rule) {
210
+ var result = '';
211
+ if (rule.required) {
212
+ result = 'required';
213
+ } else if (rule.format) {
214
+ result = 'format';
215
+ } else if (rule.arrayType) {
216
+ result = 'arrayTypeFormat';
217
+ } else if (rule.range) {
218
+ result = 'range';
219
+ } else if (rule.maximum !== undefined || rule.minimum !== undefined) {
220
+ result = 'rangeNumber';
221
+ } else if (rule.maxLength !== undefined || rule.minLength !== undefined) {
222
+ result = 'rangeLength';
223
+ } else if (rule.pattern) {
224
+ result = 'pattern';
225
+ } else if (rule.validateFunction) {
226
+ result = 'validateFunction';
227
+ }
228
+ return result;
229
+ }
230
+ }
231
+
232
+ const RuleValidatorHelper = {
233
+ required(rule, value, message) {
234
+ if (rule.required && isEmptyValue(value, rule.format || typeof value)) {
235
+ return formatMessage(rule, rule.errorMessage || message.required);
236
+ }
237
+
238
+ return null;
239
+ },
240
+
241
+ range(rule, value, message) {
242
+ const { range, errorMessage } = rule;
243
+
244
+ let list = new Array(range.length);
245
+ for (let i = 0; i < range.length; i++) {
246
+ const item = range[i];
247
+ if (types.object(item) && item.value !== undefined) {
248
+ list[i] = item.value;
249
+ } else {
250
+ list[i] = item;
251
+ }
252
+ }
253
+
254
+ let result = false;
255
+ if (Array.isArray(value)) {
256
+ result = new Set(value.concat(list)).size === list.length;
257
+ } else {
258
+ if (list.indexOf(value) > -1) {
259
+ result = true;
260
+ }
261
+ }
262
+
263
+ if (!result) {
264
+ return formatMessage(rule, errorMessage || message['enum']);
265
+ }
266
+
267
+ return null;
268
+ },
269
+
270
+ rangeNumber(rule, value, message) {
271
+ if (!types.number(value)) {
272
+ return formatMessage(rule, rule.errorMessage || message.pattern.mismatch);
273
+ }
274
+
275
+ let { minimum, maximum, exclusiveMinimum, exclusiveMaximum } = rule;
276
+ let min = exclusiveMinimum ? value <= minimum : value < minimum;
277
+ let max = exclusiveMaximum ? value >= maximum : value > maximum;
278
+
279
+ if (minimum !== undefined && min) {
280
+ return formatMessage(rule, rule.errorMessage || message['number'][exclusiveMinimum ? 'exclusiveMinimum' : 'minimum']);
281
+ } else if (maximum !== undefined && max) {
282
+ return formatMessage(rule, rule.errorMessage || message['number'][exclusiveMaximum ? 'exclusiveMaximum' : 'maximum']);
283
+ } else if (minimum !== undefined && maximum !== undefined && (min || max)) {
284
+ return formatMessage(rule, rule.errorMessage || message['number'].range);
285
+ }
286
+
287
+ return null;
288
+ },
289
+
290
+ rangeLength(rule, value, message) {
291
+ if (!types.string(value) && !types.array(value)) {
292
+ return formatMessage(rule, rule.errorMessage || message.pattern.mismatch);
293
+ }
294
+
295
+ let min = rule.minLength;
296
+ let max = rule.maxLength;
297
+ let val = value.length;
298
+
299
+ if (min !== undefined && val < min) {
300
+ return formatMessage(rule, rule.errorMessage || message['length'].minLength);
301
+ } else if (max !== undefined && val > max) {
302
+ return formatMessage(rule, rule.errorMessage || message['length'].maxLength);
303
+ } else if (min !== undefined && max !== undefined && (val < min || val > max)) {
304
+ return formatMessage(rule, rule.errorMessage || message['length'].range);
305
+ }
306
+
307
+ return null;
308
+ },
309
+
310
+ pattern(rule, value, message) {
311
+ if (!types['pattern'](rule.pattern, value)) {
312
+ return formatMessage(rule, rule.errorMessage || message.pattern.mismatch);
313
+ }
314
+
315
+ return null;
316
+ },
317
+
318
+ format(rule, value, message) {
319
+ var customTypes = Object.keys(types);
320
+ var format = FORMAT_MAPPING[rule.format] ? FORMAT_MAPPING[rule.format] : rule.format || rule.arrayType;
321
+
322
+ if (customTypes.indexOf(format) > -1) {
323
+ if (!types[format](value)) {
324
+ return formatMessage(rule, rule.errorMessage || message.typeError);
325
+ }
326
+ }
327
+
328
+ return null;
329
+ },
330
+
331
+ arrayTypeFormat(rule, value, message) {
332
+ if (!Array.isArray(value)) {
333
+ return formatMessage(rule, rule.errorMessage || message.typeError);
334
+ }
335
+
336
+ for (let i = 0; i < value.length; i++) {
337
+ const element = value[i];
338
+ let formatResult = this.format(rule, element, message);
339
+ if (formatResult !== null) {
340
+ return formatResult;
341
+ }
342
+ }
343
+
344
+ return null;
345
+ }
346
+ };
347
+
348
+ class SchemaValidator extends RuleValidator {
349
+ constructor(schema, options) {
350
+ super(SchemaValidator.message);
351
+
352
+ this._schema = schema;
353
+ this._options = options || null;
354
+ }
355
+
356
+ updateSchema(schema) {
357
+ this._schema = schema;
358
+ }
359
+
360
+ async validate(data, allData) {
361
+ let result = this._checkFieldInSchema(data);
362
+ if (!result) {
363
+ result = await this.invokeValidate(data, false, allData);
364
+ }
365
+ return result.length ? result[0] : null;
366
+ }
367
+
368
+ async validateAll(data, allData) {
369
+ let result = this._checkFieldInSchema(data);
370
+ if (!result) {
371
+ result = await this.invokeValidate(data, true, allData);
372
+ }
373
+ return result;
374
+ }
375
+
376
+ async validateUpdate(data, allData) {
377
+ let result = this._checkFieldInSchema(data);
378
+ if (!result) {
379
+ result = await this.invokeValidateUpdate(data, false, allData);
380
+ }
381
+ return result.length ? result[0] : null;
382
+ }
383
+
384
+ async invokeValidate(data, all, allData) {
385
+ let result = [];
386
+ let schema = this._schema;
387
+ for (let key in schema) {
388
+ let value = schema[key];
389
+ let errorMessage = await this.validateRule(key, value, data[key], data, allData);
390
+ if (errorMessage != null) {
391
+ result.push({
392
+ key,
393
+ errorMessage
394
+ });
395
+ if (!all) break;
396
+ }
397
+ }
398
+ return result;
399
+ }
400
+
401
+ async invokeValidateUpdate(data, all, allData) {
402
+ let result = [];
403
+ for (let key in data) {
404
+ let errorMessage = await this.validateRule(key, this._schema[key], data[key], data, allData);
405
+ if (errorMessage != null) {
406
+ result.push({
407
+ key,
408
+ errorMessage
409
+ });
410
+ if (!all) break;
411
+ }
412
+ }
413
+ return result;
414
+ }
415
+
416
+ _checkFieldInSchema(data) {
417
+ var keys = Object.keys(data);
418
+ var keys2 = Object.keys(this._schema);
419
+ if (new Set(keys.concat(keys2)).size === keys2.length) {
420
+ return '';
421
+ }
422
+
423
+ var noExistFields = keys.filter((key) => {
424
+ return keys2.indexOf(key) < 0;
425
+ });
426
+ var errorMessage = formatMessage(
427
+ {
428
+ field: JSON.stringify(noExistFields)
429
+ },
430
+ SchemaValidator.message.TAG + SchemaValidator.message['defaultInvalid']
431
+ );
432
+ return [
433
+ {
434
+ key: 'invalid',
435
+ errorMessage
436
+ }
437
+ ];
438
+ }
439
+ }
440
+
441
+ function Message() {
442
+ return {
443
+ TAG: '',
444
+ default: '验证错误',
445
+ defaultInvalid: '提交的字段{field}在数据库中并不存在',
446
+ validateFunction: '验证无效',
447
+ required: '{label}必填',
448
+ enum: '{label}超出范围',
449
+ timestamp: '{label}格式无效',
450
+ whitespace: '{label}不能为空',
451
+ typeError: '{label}类型无效',
452
+ date: {
453
+ format: '{label}日期{value}格式无效',
454
+ parse: '{label}日期无法解析,{value}无效',
455
+ invalid: '{label}日期{value}无效'
456
+ },
457
+ length: {
458
+ minLength: '{label}长度不能少于{minLength}',
459
+ maxLength: '{label}长度不能超过{maxLength}',
460
+ range: '{label}必须介于{minLength}和{maxLength}之间'
461
+ },
462
+ number: {
463
+ minimum: '{label}不能小于{minimum}',
464
+ maximum: '{label}不能大于{maximum}',
465
+ exclusiveMinimum: '{label}不能小于等于{minimum}',
466
+ exclusiveMaximum: '{label}不能大于等于{maximum}',
467
+ range: '{label}必须介于{minimum}and{maximum}之间'
468
+ },
469
+ pattern: {
470
+ mismatch: '{label}格式不匹配'
471
+ }
472
+ };
473
+ }
474
+
475
+ SchemaValidator.message = new Message();
476
+
477
+ export default SchemaValidator;
@@ -94,6 +94,7 @@ export default {
94
94
  padding: 9px;
95
95
  align-items: stretch;
96
96
  align-content: flex-start;
97
+ margin-top: 5px;
97
98
  }
98
99
  .cv-textarea__box {
99
100
  flex: 1;