项目初始化
This commit is contained in:
@@ -0,0 +1,536 @@
|
||||
<template>
|
||||
<view class="">
|
||||
<view
|
||||
class="uni-forms-item"
|
||||
:class="{
|
||||
'uni-forms-item--border': border,
|
||||
'is-first-border': border && isFirstBorder,
|
||||
'uni-forms-item-error': msg
|
||||
}"
|
||||
>
|
||||
<view class="uni-forms-item__box">
|
||||
<view class="uni-forms-item__inner" :class="['is-direction-' + labelPos]">
|
||||
<view class="uni-forms-item__label" :style="{ width: labelWid, justifyContent: justifyContent }">
|
||||
<slot name="label">
|
||||
<text v-if="required" class="is-required">*</text>
|
||||
<uni-icons
|
||||
v-if="leftIcon"
|
||||
class="label-icon"
|
||||
size="16"
|
||||
:type="leftIcon"
|
||||
:color="iconColor"
|
||||
/>
|
||||
<text class="label-text">{{ label }}</text>
|
||||
|
||||
<view v-if="label" class="label-seat"></view>
|
||||
</slot>
|
||||
</view>
|
||||
<view class="uni-forms-item__content" :class="{ 'is-input-error-border': msg }"><slot></slot></view>
|
||||
</view>
|
||||
<view
|
||||
v-if="msg"
|
||||
class="uni-error-message"
|
||||
:class="{ 'uni-error-msg--boeder': border }"
|
||||
:style="{
|
||||
paddingLeft: labelLeft
|
||||
}"
|
||||
>
|
||||
<text class="uni-error-message-text">{{ showMsg === 'undertext' ? msg : '' }}</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
/**
|
||||
* Field 输入框
|
||||
* @description 此组件可以实现表单的输入与校验,包括 "text" 和 "textarea" 类型。
|
||||
* @tutorial https://ext.dcloud.net.cn/plugin?id=21001
|
||||
* @property {Boolean} required 是否必填,左边显示红色"*"号(默认false)
|
||||
* @property {String} validateTrigger = [bind|submit] 校验触发器方式 默认 submit 可选
|
||||
* @value bind 发生变化时触发
|
||||
* @value submit 提交时触发
|
||||
* @property {String } leftIcon label左边的图标,限 uni-ui 的图标名称
|
||||
* @property {String } iconColor 左边通过icon配置的图标的颜色(默认#606266)
|
||||
* @property {String } label 输入框左边的文字提示
|
||||
* @property {Number } labelWidth label的宽度,单位px(默认65)
|
||||
* @property {String } labelAlign = [left|center|right] label的文字对齐方式(默认left)
|
||||
* @value left label 左侧显示
|
||||
* @value center label 居中
|
||||
* @value right label 右侧对齐
|
||||
* @property {String } labelPosition = [top|left] label的文字的位置(默认left)
|
||||
* @value top 顶部显示 label
|
||||
* @value left 左侧显示 label
|
||||
* @property {String } errorMessage 显示的错误提示内容,如果为空字符串或者false,则不显示错误信息
|
||||
* @property {String } name 表单域的属性名,在使用校验规则时必填
|
||||
*/
|
||||
|
||||
export default {
|
||||
name: 'uniFormsItem',
|
||||
props: {
|
||||
// 自定义内容
|
||||
custom: {
|
||||
type: Boolean,
|
||||
default: false
|
||||
},
|
||||
// 是否显示报错信息
|
||||
showMessage: {
|
||||
type: Boolean,
|
||||
default: true
|
||||
},
|
||||
name: String,
|
||||
required: Boolean,
|
||||
validateTrigger: {
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
leftIcon: String,
|
||||
iconColor: {
|
||||
type: String,
|
||||
default: '#606266'
|
||||
},
|
||||
label: String,
|
||||
// 左边标题的宽度单位px
|
||||
labelWidth: {
|
||||
type: [Number, String],
|
||||
default: ''
|
||||
},
|
||||
// 对齐方式,left|center|right
|
||||
labelAlign: {
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
// lable的位置,可选为 left-左边,top-上边
|
||||
labelPosition: {
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
errorMessage: {
|
||||
type: [String, Boolean],
|
||||
default: ''
|
||||
},
|
||||
// 表单校验规则
|
||||
rules: {
|
||||
type: Array,
|
||||
default() {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
errorTop: false,
|
||||
errorBottom: false,
|
||||
labelMarginBottom: '',
|
||||
errorWidth: '',
|
||||
errMsg: '',
|
||||
val: '',
|
||||
labelPos: '',
|
||||
labelWid: '',
|
||||
labelAli: '',
|
||||
showMsg: 'undertext',
|
||||
border: false,
|
||||
isFirstBorder: false,
|
||||
isArray: false,
|
||||
arrayField: ''
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
msg() {
|
||||
return this.errorMessage || this.errMsg;
|
||||
},
|
||||
fieldStyle() {
|
||||
let style = {};
|
||||
if (this.labelPos == 'top') {
|
||||
style.padding = '0 0';
|
||||
this.labelMarginBottom = '6px';
|
||||
}
|
||||
if (this.labelPos == 'left' && this.msg !== false && this.msg != '') {
|
||||
style.paddingBottom = '0px';
|
||||
this.errorBottom = true;
|
||||
this.errorTop = false;
|
||||
} else if (this.labelPos == 'top' && this.msg !== false && this.msg != '') {
|
||||
this.errorBottom = false;
|
||||
this.errorTop = true;
|
||||
} else {
|
||||
// style.paddingBottom = ''
|
||||
this.errorTop = false;
|
||||
this.errorBottom = false;
|
||||
}
|
||||
return style;
|
||||
},
|
||||
|
||||
// uni不支持在computed中写style.justifyContent = 'center'的形式,故用此方法
|
||||
justifyContent() {
|
||||
if (this.labelAli === 'left') return 'flex-start';
|
||||
if (this.labelAli === 'center') return 'center';
|
||||
if (this.labelAli === 'right') return 'flex-end';
|
||||
},
|
||||
labelLeft() {
|
||||
return (this.labelPos === 'left' ? parseInt(this.labelWid) : 0) + 'rpx';
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
validateTrigger(trigger) {
|
||||
this.formTrigger = trigger;
|
||||
}
|
||||
},
|
||||
created() {
|
||||
this.form = this.getForm();
|
||||
this.group = this.getForm('uniGroup');
|
||||
this.formRules = [];
|
||||
this.formTrigger = this.validateTrigger;
|
||||
// 处理 name,是否数组
|
||||
if (this.name && this.name.indexOf('[') !== -1 && this.name.indexOf(']') !== -1) {
|
||||
this.isArray = true;
|
||||
this.arrayField = this.name;
|
||||
// fix by mehaotian 修改不修改的情况,动态值不检验的问题
|
||||
this.form.formData[this.name] = this.form._getValue(this.name, '');
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
if (this.form) {
|
||||
this.form.childrens.push(this);
|
||||
}
|
||||
this.init();
|
||||
},
|
||||
// #ifndef VUE3
|
||||
destroyed() {
|
||||
if (this.__isUnmounted) return;
|
||||
this.unInit();
|
||||
},
|
||||
// #endif
|
||||
// #ifdef VUE3
|
||||
unmounted() {
|
||||
this.__isUnmounted = true;
|
||||
this.unInit();
|
||||
},
|
||||
// #endif
|
||||
methods: {
|
||||
init() {
|
||||
if (this.form) {
|
||||
let {
|
||||
formRules,
|
||||
validator,
|
||||
formData,
|
||||
value,
|
||||
labelPosition,
|
||||
labelWidth,
|
||||
labelAlign,
|
||||
errShowType
|
||||
} = this.form;
|
||||
this.labelPos = this.labelPosition ? this.labelPosition : labelPosition;
|
||||
|
||||
if (this.label) {
|
||||
this.labelWid = this.labelWidth ? this.labelWidth : labelWidth || 140;
|
||||
} else {
|
||||
this.labelWid = this.labelWidth ? this.labelWidth : labelWidth || 'auto';
|
||||
}
|
||||
if (this.labelWid && this.labelWid !== 'auto') {
|
||||
this.labelWid += 'rpx';
|
||||
}
|
||||
this.labelAli = this.labelAlign ? this.labelAlign : labelAlign;
|
||||
|
||||
// 判断第一个 item
|
||||
if (!this.form.isFirstBorder) {
|
||||
this.form.isFirstBorder = true;
|
||||
this.isFirstBorder = true;
|
||||
}
|
||||
|
||||
// 判断 group 里的第一个 item
|
||||
if (this.group) {
|
||||
if (!this.group.isFirstBorder) {
|
||||
this.group.isFirstBorder = true;
|
||||
this.isFirstBorder = true;
|
||||
}
|
||||
}
|
||||
|
||||
this.border = this.form.border;
|
||||
this.showMsg = errShowType;
|
||||
let name = this.isArray ? this.arrayField : this.name;
|
||||
if (!name) return;
|
||||
if (formRules && this.rules.length > 0) {
|
||||
if (!formRules[name]) {
|
||||
formRules[name] = {
|
||||
rules: this.rules
|
||||
};
|
||||
}
|
||||
validator.updateSchema(formRules);
|
||||
}
|
||||
this.formRules = formRules[name] || {};
|
||||
this.validator = validator;
|
||||
} else {
|
||||
this.labelPos = this.labelPosition || 'left';
|
||||
this.labelWid = this.labelWidth || 130;
|
||||
this.labelAli = this.labelAlign || 'left';
|
||||
}
|
||||
},
|
||||
unInit() {
|
||||
if (this.form) {
|
||||
this.form.childrens.forEach((item, index) => {
|
||||
if (item === this) {
|
||||
this.form.childrens.splice(index, 1);
|
||||
delete this.form.formData[item.name];
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
/**
|
||||
* 获取父元素实例
|
||||
*/
|
||||
getForm(name = 'uniForms') {
|
||||
let parent = this.$parent;
|
||||
let parentName = parent.$options.name;
|
||||
while (parentName !== name) {
|
||||
parent = parent.$parent;
|
||||
if (!parent) return false;
|
||||
parentName = parent.$options.name;
|
||||
}
|
||||
return parent;
|
||||
},
|
||||
|
||||
/**
|
||||
* 移除该表单项的校验结果
|
||||
*/
|
||||
clearValidate() {
|
||||
this.errMsg = '';
|
||||
},
|
||||
/**
|
||||
* 子组件调用,如 easyinput
|
||||
* @param {Object} value
|
||||
*/
|
||||
setValue(value) {
|
||||
let name = this.isArray ? this.arrayField : this.name;
|
||||
if (name) {
|
||||
if (this.errMsg) this.errMsg = '';
|
||||
// 给组件赋值
|
||||
this.form.formData[name] = this.form._getValue(name, value);
|
||||
if (!this.formRules || (typeof this.formRules && JSON.stringify(this.formRules) === '{}')) return;
|
||||
this.triggerCheck(this.form._getValue(this.name, value));
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 校验规则
|
||||
* @param {Object} value
|
||||
*/
|
||||
async triggerCheck(value, formTrigger) {
|
||||
let promise = null;
|
||||
this.errMsg = '';
|
||||
// fix by mehaotian 解决没有检验规则的情况下,抛出错误的问题
|
||||
if (!this.validator || Object.keys(this.formRules).length === 0) return;
|
||||
const isNoField = this.isRequired(this.formRules.rules || []);
|
||||
let isTrigger = this.isTrigger(
|
||||
this.formRules.validateTrigger,
|
||||
this.validateTrigger,
|
||||
this.form.validateTrigger
|
||||
);
|
||||
let result = null;
|
||||
if (!!isTrigger || formTrigger) {
|
||||
let name = this.isArray ? this.arrayField : this.name;
|
||||
result = await this.validator.validateUpdate(
|
||||
{
|
||||
[name]: value
|
||||
},
|
||||
this.form.formData
|
||||
);
|
||||
}
|
||||
// 判断是否必填,非必填,不填不校验,填写才校验
|
||||
if (!isNoField && (value === undefined || value === '')) {
|
||||
result = null;
|
||||
}
|
||||
const inputComp = this.form.inputChildrens.find(child => child.rename === this.name);
|
||||
if ((isTrigger || formTrigger) && result && result.errorMessage) {
|
||||
if (inputComp) {
|
||||
inputComp.errMsg = result.errorMessage;
|
||||
}
|
||||
if (this.form.errShowType === 'toast') {
|
||||
uni.showToast({
|
||||
title: result.errorMessage || '校验错误',
|
||||
icon: 'none'
|
||||
});
|
||||
}
|
||||
if (this.form.errShowType === 'modal') {
|
||||
uni.showModal({
|
||||
title: '提示',
|
||||
content: result.errorMessage || '校验错误'
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (inputComp) {
|
||||
inputComp.errMsg = '';
|
||||
}
|
||||
}
|
||||
|
||||
this.errMsg = !result ? '' : result.errorMessage;
|
||||
// 触发validate事件
|
||||
this.form.validateCheck(result ? result : null);
|
||||
// typeof callback === 'function' && callback(result ? result : null);
|
||||
// if (promise) return promise
|
||||
return result ? result : null;
|
||||
},
|
||||
/**
|
||||
* 触发时机
|
||||
* @param {Object} event
|
||||
*/
|
||||
isTrigger(rule, itemRlue, parentRule) {
|
||||
let rl = true;
|
||||
// bind submit
|
||||
if (rule === 'submit' || !rule) {
|
||||
if (rule === undefined) {
|
||||
if (itemRlue !== 'bind') {
|
||||
if (!itemRlue) {
|
||||
return parentRule === 'bind' ? true : false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
// 是否有必填字段
|
||||
isRequired(rules) {
|
||||
let isNoField = false;
|
||||
for (let i = 0; i < rules.length; i++) {
|
||||
const ruleData = rules[i];
|
||||
if (ruleData.required) {
|
||||
isNoField = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return isNoField;
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="scss">
|
||||
.uni-forms-item {
|
||||
position: relative;
|
||||
padding: 0px;
|
||||
text-align: left;
|
||||
color: #333;
|
||||
font-size: 14px;
|
||||
// margin-bottom: 22px;
|
||||
}
|
||||
|
||||
.uni-forms-item__box {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.uni-forms-item__inner {
|
||||
/* #ifndef APP-NVUE */
|
||||
display: flex;
|
||||
/* #endif */
|
||||
// flex-direction: row;
|
||||
// align-items: center;
|
||||
padding-bottom: 22px;
|
||||
// margin-bottom: 22px;
|
||||
}
|
||||
|
||||
.is-direction-left {
|
||||
flex-direction: row;
|
||||
}
|
||||
|
||||
.is-direction-top {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.uni-forms-item__label {
|
||||
/* #ifndef APP-NVUE */
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
box-sizing: border-box;
|
||||
/* #endif */
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
width: 65px;
|
||||
// line-height: 2;
|
||||
// margin-top: 3px;
|
||||
padding: 5px 0;
|
||||
height: 72rpx;
|
||||
// margin-right: 5px;
|
||||
|
||||
.label-text {
|
||||
font-size: 28rpx;
|
||||
color: #333333;
|
||||
}
|
||||
.label-seat {
|
||||
margin-right: 5px;
|
||||
}
|
||||
}
|
||||
|
||||
.uni-forms-item__content {
|
||||
/* #ifndef APP-NVUE */
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
min-height: 36px;
|
||||
/* #endif */
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.label-icon {
|
||||
margin-right: 5px;
|
||||
margin-top: -1px;
|
||||
}
|
||||
|
||||
// 必填
|
||||
.is-required {
|
||||
// color: $uni-color-error;
|
||||
color: #dd524d;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.uni-error-message {
|
||||
position: absolute;
|
||||
bottom: 0px;
|
||||
left: 0;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.uni-error-message-text {
|
||||
line-height: 44rpx;
|
||||
color: #dd524d;
|
||||
font-size: 24rpx;
|
||||
}
|
||||
|
||||
.uni-error-msg--boeder {
|
||||
position: relative;
|
||||
bottom: 0;
|
||||
line-height: 22px;
|
||||
}
|
||||
|
||||
.is-input-error-border {
|
||||
border-color: #dd524d;
|
||||
}
|
||||
|
||||
.uni-forms-item--border {
|
||||
margin-bottom: 0;
|
||||
padding: 10px 0;
|
||||
border-top: 1px #eee solid;
|
||||
|
||||
.uni-forms-item__inner {
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.uni-forms-item-error {
|
||||
// padding-bottom: 0;
|
||||
}
|
||||
|
||||
.is-first-border {
|
||||
/* #ifndef APP-NVUE */
|
||||
border: none;
|
||||
/* #endif */
|
||||
/* #ifdef APP-NVUE */
|
||||
border-width: 0;
|
||||
/* #endif */
|
||||
}
|
||||
|
||||
.uni-forms--no-padding {
|
||||
padding: 0;
|
||||
}
|
||||
</style>
|
472
uni_modules/uni-forms/components/uni-forms/uni-forms.vue
Normal file
472
uni_modules/uni-forms/components/uni-forms/uni-forms.vue
Normal file
@@ -0,0 +1,472 @@
|
||||
<template>
|
||||
<view class="uni-forms" :class="{ 'uni-forms--top': !border }">
|
||||
<form @submit.stop="submitForm" @reset="resetForm">
|
||||
<slot></slot>
|
||||
</form>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
// #ifndef VUE3
|
||||
import Vue from 'vue';
|
||||
Vue.prototype.binddata = function(name, value, formName) {
|
||||
if (formName) {
|
||||
this.$refs[formName].setValue(name, value);
|
||||
} else {
|
||||
let formVm;
|
||||
for (let i in this.$refs) {
|
||||
const vm = this.$refs[i];
|
||||
if (vm && vm.$options && vm.$options.name === 'uniForms') {
|
||||
formVm = vm;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!formVm) return console.error('当前 uni-froms 组件缺少 ref 属性');
|
||||
formVm.setValue(name, value);
|
||||
}
|
||||
};
|
||||
// #endif
|
||||
|
||||
|
||||
|
||||
import Validator from './validate.js';
|
||||
/**
|
||||
* Forms 表单
|
||||
* @description 由输入框、选择器、单选框、多选框等控件组成,用以收集、校验、提交数据
|
||||
* @tutorial https://ext.dcloud.net.cn/plugin?id=2773
|
||||
* @property {Object} rules 表单校验规则
|
||||
* @property {String} validateTrigger = [bind|submit] 校验触发器方式 默认 submit
|
||||
* @value bind 发生变化时触发
|
||||
* @value submit 提交时触发
|
||||
* @property {String} labelPosition = [top|left] label 位置 默认 left
|
||||
* @value top 顶部显示 label
|
||||
* @value left 左侧显示 label
|
||||
* @property {String} labelWidth label 宽度,默认 65px
|
||||
* @property {String} labelAlign = [left|center|right] label 居中方式 默认 left
|
||||
* @value left label 左侧显示
|
||||
* @value center label 居中
|
||||
* @value right label 右侧对齐
|
||||
* @property {String} errShowType = [undertext|toast|modal] 校验错误信息提示方式
|
||||
* @value undertext 错误信息在底部显示
|
||||
* @value toast 错误信息toast显示
|
||||
* @value modal 错误信息modal显示
|
||||
* @event {Function} submit 提交时触发
|
||||
*/
|
||||
|
||||
export default {
|
||||
name: 'uniForms',
|
||||
components: {},
|
||||
emits:['input','reset','validate','submit'],
|
||||
props: {
|
||||
// 即将弃用
|
||||
value: {
|
||||
type: Object,
|
||||
default () {
|
||||
return {};
|
||||
}
|
||||
},
|
||||
// 替换 value 属性
|
||||
modelValue: {
|
||||
type: Object,
|
||||
default () {
|
||||
return {};
|
||||
}
|
||||
},
|
||||
// 表单校验规则
|
||||
rules: {
|
||||
type: Object,
|
||||
default () {
|
||||
return {};
|
||||
}
|
||||
},
|
||||
// 校验触发器方式,默认 关闭
|
||||
validateTrigger: {
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
// label 位置,可选值 top/left
|
||||
labelPosition: {
|
||||
type: String,
|
||||
default: 'left'
|
||||
},
|
||||
// label 宽度,单位 px
|
||||
labelWidth: {
|
||||
type: [String, Number],
|
||||
default: ''
|
||||
},
|
||||
// label 居中方式,可选值 left/center/right
|
||||
labelAlign: {
|
||||
type: String,
|
||||
default: 'left'
|
||||
},
|
||||
errShowType: {
|
||||
type: String,
|
||||
default: 'undertext'
|
||||
},
|
||||
border: {
|
||||
type: Boolean,
|
||||
default: false
|
||||
}
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
formData: {}
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
dataValue() {
|
||||
if (JSON.stringify(this.modelValue) === '{}') {
|
||||
return this.value
|
||||
} else {
|
||||
return this.modelValue
|
||||
}
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
rules(newVal) {
|
||||
// 如果规则发生变化,要初始化组件
|
||||
this.init(newVal);
|
||||
},
|
||||
labelPosition() {
|
||||
this.childrens.forEach(vm => {
|
||||
vm.init()
|
||||
})
|
||||
}
|
||||
},
|
||||
created() {
|
||||
// #ifdef VUE3
|
||||
let getbinddata = getApp().$vm.$.appContext.config.globalProperties.binddata
|
||||
if (!getbinddata) {
|
||||
getApp().$vm.$.appContext.config.globalProperties.binddata = function(name, value, formName) {
|
||||
if (formName) {
|
||||
this.$refs[formName].setValue(name, value);
|
||||
} else {
|
||||
let formVm;
|
||||
for (let i in this.$refs) {
|
||||
const vm = this.$refs[i];
|
||||
if (vm && vm.$options && vm.$options.name === 'uniForms') {
|
||||
formVm = vm;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!formVm) return console.error('当前 uni-froms 组件缺少 ref 属性');
|
||||
formVm.setValue(name, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
// #endif
|
||||
|
||||
// 存放watch 监听数组
|
||||
this.unwatchs = [];
|
||||
// 存放子组件数组
|
||||
this.childrens = [];
|
||||
// 存放 easyInput 组件
|
||||
this.inputChildrens = [];
|
||||
// 存放 dataCheckbox 组件
|
||||
this.checkboxChildrens = [];
|
||||
// 存放规则
|
||||
this.formRules = [];
|
||||
this.init(this.rules);
|
||||
},
|
||||
// mounted() {
|
||||
// this.init(this.rules)
|
||||
// },
|
||||
methods: {
|
||||
init(formRules) {
|
||||
// 判断是否有规则
|
||||
if (Object.keys(formRules).length === 0) {
|
||||
this.formData = this.dataValue
|
||||
return
|
||||
};
|
||||
this.formRules = formRules;
|
||||
this.validator = new Validator(formRules);
|
||||
this.registerWatch();
|
||||
},
|
||||
// 监听 watch
|
||||
registerWatch() {
|
||||
// 取消监听,避免多次调用 init 重复执行 $watch
|
||||
this.unwatchs.forEach(v => v());
|
||||
this.childrens.forEach((v) => {
|
||||
v.init()
|
||||
})
|
||||
// watch 每个属性 ,需要知道具体那个属性发变化
|
||||
Object.keys(this.dataValue).forEach(key => {
|
||||
let watch = this.$watch(
|
||||
'dataValue.' + key,
|
||||
value => {
|
||||
if (!value) return
|
||||
// 如果是对象 ,则平铺内容
|
||||
if (value.toString() === '[object Object]') {
|
||||
for (let i in value) {
|
||||
let name = `${key}[${i}]`;
|
||||
this.formData[name] = this._getValue(name, value[i]);
|
||||
}
|
||||
} else {
|
||||
this.formData[key] = this._getValue(key, value);
|
||||
}
|
||||
},
|
||||
{
|
||||
deep: true,
|
||||
immediate: true
|
||||
}
|
||||
);
|
||||
this.unwatchs.push(watch);
|
||||
});
|
||||
},
|
||||
/**
|
||||
* 公开给用户使用
|
||||
* 设置校验规则
|
||||
* @param {Object} formRules
|
||||
*/
|
||||
setRules(formRules) {
|
||||
this.init(formRules);
|
||||
},
|
||||
/**
|
||||
* 公开给用户使用
|
||||
* 设置自定义表单组件 value 值
|
||||
* @param {String} name 字段名称
|
||||
* @param {String} value 字段值
|
||||
*/
|
||||
setValue(name, value, callback) {
|
||||
let example = this.childrens.find(child => child.name === name);
|
||||
if (!example) return null;
|
||||
value = this._getValue(example.name, value);
|
||||
this.formData[name] = value;
|
||||
example.val = value;
|
||||
return example.triggerCheck(value, callback);
|
||||
},
|
||||
|
||||
/**
|
||||
* 表单重置
|
||||
* @param {Object} event
|
||||
*/
|
||||
resetForm(event) {
|
||||
this.childrens.forEach(item => {
|
||||
item.errMsg = '';
|
||||
const inputComp = this.inputChildrens.find(child => child.rename === item.name);
|
||||
if (inputComp) {
|
||||
inputComp.errMsg = '';
|
||||
// fix by mehaotian 不触发其他组件的 setValue
|
||||
inputComp.is_reset = true
|
||||
inputComp.$emit('input', inputComp.multiple ? [] : '');
|
||||
inputComp.$emit('update:modelValue', inputComp.multiple ? [] : '');
|
||||
}
|
||||
});
|
||||
|
||||
this.childrens.forEach(item => {
|
||||
if (item.name) {
|
||||
this.formData[item.name] = this._getValue(item.name, '');
|
||||
}
|
||||
});
|
||||
|
||||
this.$emit('reset', event);
|
||||
},
|
||||
|
||||
/**
|
||||
* 触发表单校验,通过 @validate 获取
|
||||
* @param {Object} validate
|
||||
*/
|
||||
validateCheck(validate) {
|
||||
if (validate === null) validate = null;
|
||||
this.$emit('validate', validate);
|
||||
},
|
||||
/**
|
||||
* 校验所有或者部分表单
|
||||
*/
|
||||
async validateAll(invalidFields, type, keepitem, callback) {
|
||||
let childrens = []
|
||||
for (let i in invalidFields) {
|
||||
const item = this.childrens.find(v => v.name === i)
|
||||
if (item) {
|
||||
childrens.push(item)
|
||||
}
|
||||
}
|
||||
|
||||
if (!callback && typeof keepitem === 'function') {
|
||||
callback = keepitem;
|
||||
}
|
||||
|
||||
let promise;
|
||||
if (!callback && typeof callback !== 'function' && Promise) {
|
||||
promise = new Promise((resolve, reject) => {
|
||||
callback = function(valid, invalidFields) {
|
||||
!valid ? resolve(invalidFields) : reject(valid);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
let results = [];
|
||||
let newFormData = {};
|
||||
if (this.validator) {
|
||||
for (let key in childrens) {
|
||||
const child = childrens[key];
|
||||
let name = child.isArray ? child.arrayField : child.name;
|
||||
if (child.isArray) {
|
||||
if (child.name.indexOf('[') !== -1 && child.name.indexOf(']') !== -1) {
|
||||
const fieldData = child.name.split('[');
|
||||
const fieldName = fieldData[0];
|
||||
const fieldValue = fieldData[1].replace(']', '');
|
||||
if (!newFormData[fieldName]) {
|
||||
newFormData[fieldName] = {};
|
||||
}
|
||||
newFormData[fieldName][fieldValue] = this._getValue(name, invalidFields[name]);
|
||||
}
|
||||
} else {
|
||||
newFormData[name] = this._getValue(name, invalidFields[name]);
|
||||
}
|
||||
const result = await child.triggerCheck(invalidFields[name], true);
|
||||
if (result) {
|
||||
results.push(result);
|
||||
if (this.errShowType === 'toast' || this.errShowType === 'modal') break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
newFormData = invalidFields
|
||||
}
|
||||
if (Array.isArray(results)) {
|
||||
if (results.length === 0) results = null;
|
||||
}
|
||||
|
||||
if (Array.isArray(keepitem)) {
|
||||
keepitem.forEach(v => {
|
||||
newFormData[v] = this.dataValue[v];
|
||||
});
|
||||
}
|
||||
|
||||
if (type === 'submit') {
|
||||
this.$emit('submit', {
|
||||
detail: {
|
||||
value: newFormData,
|
||||
errors: results
|
||||
}
|
||||
});
|
||||
} else {
|
||||
this.$emit('validate', results);
|
||||
}
|
||||
|
||||
callback && typeof callback === 'function' && callback(results, newFormData);
|
||||
|
||||
if (promise && callback) {
|
||||
return promise;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
submitForm() {},
|
||||
/**
|
||||
* 外部调用方法
|
||||
* 手动提交校验表单
|
||||
* 对整个表单进行校验的方法,参数为一个回调函数。
|
||||
*/
|
||||
submit(keepitem, callback, type) {
|
||||
for (let i in this.dataValue) {
|
||||
const itemData = this.childrens.find(v => v.name === i);
|
||||
if (itemData) {
|
||||
if (this.formData[i] === undefined) {
|
||||
this.formData[i] = this._getValue(i, this.dataValue[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!type) {
|
||||
console.warn('submit 方法即将废弃,请使用validate方法代替!');
|
||||
}
|
||||
return this.validateAll(this.formData, 'submit', keepitem, callback);
|
||||
},
|
||||
|
||||
/**
|
||||
* 外部调用方法
|
||||
* 校验表单
|
||||
* 对整个表单进行校验的方法,参数为一个回调函数。
|
||||
*/
|
||||
validate(keepitem, callback) {
|
||||
return this.submit(keepitem, callback, true);
|
||||
},
|
||||
|
||||
/**
|
||||
* 部分表单校验
|
||||
* @param {Object} props
|
||||
* @param {Object} cb
|
||||
*/
|
||||
validateField(props, callback) {
|
||||
props = [].concat(props);
|
||||
let invalidFields = {};
|
||||
this.childrens.forEach(item => {
|
||||
if (props.indexOf(item.name) !== -1) {
|
||||
invalidFields = Object.assign({}, invalidFields, {
|
||||
[item.name]: this.formData[item.name]
|
||||
});
|
||||
}
|
||||
});
|
||||
return this.validateAll(invalidFields, 'submit', [], callback);
|
||||
},
|
||||
|
||||
/**
|
||||
* 对整个表单进行重置,将所有字段值重置为初始值并移除校验结果
|
||||
*/
|
||||
resetFields() {
|
||||
this.resetForm();
|
||||
},
|
||||
|
||||
/**
|
||||
* 移除表单项的校验结果。传入待移除的表单项的 prop 属性或者 prop 组成的数组,如不传则移除整个表单的校验结果
|
||||
*/
|
||||
clearValidate(props) {
|
||||
props = [].concat(props);
|
||||
this.childrens.forEach(item => {
|
||||
const inputComp = this.inputChildrens.find(child => child.rename === item.name);
|
||||
if (props.length === 0) {
|
||||
item.errMsg = '';
|
||||
if (inputComp) {
|
||||
inputComp.errMsg = '';
|
||||
}
|
||||
} else {
|
||||
if (props.indexOf(item.name) !== -1) {
|
||||
item.errMsg = '';
|
||||
if (inputComp) {
|
||||
inputComp.errMsg = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
/**
|
||||
* 把 value 转换成指定的类型
|
||||
* @param {Object} key
|
||||
* @param {Object} value
|
||||
*/
|
||||
_getValue(key, value) {
|
||||
const rules = (this.formRules[key] && this.formRules[key].rules) || [];
|
||||
const isRuleNum = rules.find(val => val.format && this.type_filter(val.format));
|
||||
const isRuleBool = rules.find(val => (val.format && val.format === 'boolean') || val.format === 'bool');
|
||||
// 输入值为 number
|
||||
if (isRuleNum) {
|
||||
value = isNaN(value) ? value : value === '' || value === null ? null : Number(value);
|
||||
}
|
||||
// 简单判断真假值
|
||||
if (isRuleBool) {
|
||||
value = !value ? false : true;
|
||||
}
|
||||
return value;
|
||||
},
|
||||
/**
|
||||
* 过滤数字类型
|
||||
* @param {Object} format
|
||||
*/
|
||||
type_filter(format) {
|
||||
return format === 'int' || format === 'double' || format === 'number' || format === 'timestamp';
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="scss" >
|
||||
.uni-forms {
|
||||
// overflow: hidden;
|
||||
// padding: 10px 15px;
|
||||
}
|
||||
|
||||
.uni-forms--top {
|
||||
// padding: 10px 15px;
|
||||
// padding-top: 22px;
|
||||
}
|
||||
</style>
|
486
uni_modules/uni-forms/components/uni-forms/validate.js
Normal file
486
uni_modules/uni-forms/components/uni-forms/validate.js
Normal file
@@ -0,0 +1,486 @@
|
||||
var pattern = {
|
||||
email: /^\S+?@\S+?\.\S+?$/,
|
||||
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]$/,
|
||||
url: new RegExp(
|
||||
"^(?!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]*)?$",
|
||||
'i')
|
||||
};
|
||||
|
||||
const FORMAT_MAPPING = {
|
||||
"int": 'integer',
|
||||
"bool": 'boolean',
|
||||
"double": 'number',
|
||||
"long": 'number',
|
||||
"password": 'string'
|
||||
// "fileurls": 'array'
|
||||
}
|
||||
|
||||
function formatMessage(args, resources = '') {
|
||||
var defaultMessage = ['label']
|
||||
defaultMessage.forEach((item) => {
|
||||
if (args[item] === undefined) {
|
||||
args[item] = ''
|
||||
}
|
||||
})
|
||||
|
||||
let str = resources
|
||||
for (let key in args) {
|
||||
let reg = new RegExp('{' + key + '}')
|
||||
str = str.replace(reg, args[key])
|
||||
}
|
||||
return str
|
||||
}
|
||||
|
||||
function isEmptyValue(value, type) {
|
||||
if (value === undefined || value === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof value === 'string' && !value) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (Array.isArray(value) && !value.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type === 'object' && !Object.keys(value).length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
const types = {
|
||||
integer(value) {
|
||||
return types.number(value) && parseInt(value, 10) === value;
|
||||
},
|
||||
string(value) {
|
||||
return typeof value === 'string';
|
||||
},
|
||||
number(value) {
|
||||
if (isNaN(value)) {
|
||||
return false;
|
||||
}
|
||||
return typeof value === 'number';
|
||||
},
|
||||
"boolean": function(value) {
|
||||
return typeof value === 'boolean';
|
||||
},
|
||||
"float": function(value) {
|
||||
return types.number(value) && !types.integer(value);
|
||||
},
|
||||
array(value) {
|
||||
return Array.isArray(value);
|
||||
},
|
||||
object(value) {
|
||||
return typeof value === 'object' && !types.array(value);
|
||||
},
|
||||
date(value) {
|
||||
return value instanceof Date;
|
||||
},
|
||||
timestamp(value) {
|
||||
if (!this.integer(value) || Math.abs(value).toString().length > 16) {
|
||||
return false
|
||||
}
|
||||
return true;
|
||||
},
|
||||
file(value) {
|
||||
return typeof value.url === 'string';
|
||||
},
|
||||
email(value) {
|
||||
return typeof value === 'string' && !!value.match(pattern.email) && value.length < 255;
|
||||
},
|
||||
url(value) {
|
||||
return typeof value === 'string' && !!value.match(pattern.url);
|
||||
},
|
||||
pattern(reg, value) {
|
||||
try {
|
||||
return new RegExp(reg).test(value);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
method(value) {
|
||||
return typeof value === 'function';
|
||||
},
|
||||
idcard(value) {
|
||||
return typeof value === 'string' && !!value.match(pattern.idcard);
|
||||
},
|
||||
'url-https'(value) {
|
||||
return this.url(value) && value.startsWith('https://');
|
||||
},
|
||||
'url-scheme'(value) {
|
||||
return value.startsWith('://');
|
||||
},
|
||||
'url-web'(value) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
class RuleValidator {
|
||||
|
||||
constructor(message) {
|
||||
this._message = message
|
||||
}
|
||||
|
||||
async validateRule(fieldKey, fieldValue, value, data, allData) {
|
||||
var result = null
|
||||
|
||||
let rules = fieldValue.rules
|
||||
|
||||
let hasRequired = rules.findIndex((item) => {
|
||||
return item.required
|
||||
})
|
||||
if (hasRequired < 0) {
|
||||
if (value === null || value === undefined) {
|
||||
return result
|
||||
}
|
||||
if (typeof value === 'string' && !value.length) {
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
var message = this._message
|
||||
|
||||
if (rules === undefined) {
|
||||
return message['default']
|
||||
}
|
||||
|
||||
for (var i = 0; i < rules.length; i++) {
|
||||
let rule = rules[i]
|
||||
let vt = this._getValidateType(rule)
|
||||
|
||||
Object.assign(rule, {
|
||||
label: fieldValue.label || `["${fieldKey}"]`
|
||||
})
|
||||
|
||||
if (RuleValidatorHelper[vt]) {
|
||||
result = RuleValidatorHelper[vt](rule, value, message)
|
||||
if (result != null) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (rule.validateExpr) {
|
||||
let now = Date.now()
|
||||
let resultExpr = rule.validateExpr(value, allData, now)
|
||||
if (resultExpr === false) {
|
||||
result = this._getMessage(rule, rule.errorMessage || this._message['default'])
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (rule.validateFunction) {
|
||||
result = await this.validateFunction(rule, value, data, allData, vt)
|
||||
if (result !== null) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (result !== null) {
|
||||
result = message.TAG + result
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
async validateFunction(rule, value, data, allData, vt) {
|
||||
let result = null
|
||||
try {
|
||||
let callbackMessage = null
|
||||
const res = await rule.validateFunction(rule, value, allData || data, (message) => {
|
||||
callbackMessage = message
|
||||
})
|
||||
if (callbackMessage || (typeof res === 'string' && res) || res === false) {
|
||||
result = this._getMessage(rule, callbackMessage || res, vt)
|
||||
}
|
||||
} catch (e) {
|
||||
result = this._getMessage(rule, e.message, vt)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
_getMessage(rule, message, vt) {
|
||||
return formatMessage(rule, message || rule.errorMessage || this._message[vt] || message['default'])
|
||||
}
|
||||
|
||||
_getValidateType(rule) {
|
||||
var result = ''
|
||||
if (rule.required) {
|
||||
result = 'required'
|
||||
} else if (rule.format) {
|
||||
result = 'format'
|
||||
} else if (rule.arrayType) {
|
||||
result = 'arrayTypeFormat'
|
||||
} else if (rule.range) {
|
||||
result = 'range'
|
||||
} else if (rule.maximum !== undefined || rule.minimum !== undefined) {
|
||||
result = 'rangeNumber'
|
||||
} else if (rule.maxLength !== undefined || rule.minLength !== undefined) {
|
||||
result = 'rangeLength'
|
||||
} else if (rule.pattern) {
|
||||
result = 'pattern'
|
||||
} else if (rule.validateFunction) {
|
||||
result = 'validateFunction'
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
const RuleValidatorHelper = {
|
||||
required(rule, value, message) {
|
||||
if (rule.required && isEmptyValue(value, rule.format || typeof value)) {
|
||||
return formatMessage(rule, rule.errorMessage || message.required);
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
|
||||
range(rule, value, message) {
|
||||
const {
|
||||
range,
|
||||
errorMessage
|
||||
} = rule;
|
||||
|
||||
let list = new Array(range.length);
|
||||
for (let i = 0; i < range.length; i++) {
|
||||
const item = range[i];
|
||||
if (types.object(item) && item.value !== undefined) {
|
||||
list[i] = item.value;
|
||||
} else {
|
||||
list[i] = item;
|
||||
}
|
||||
}
|
||||
|
||||
let result = false
|
||||
if (Array.isArray(value)) {
|
||||
result = (new Set(value.concat(list)).size === list.length);
|
||||
} else {
|
||||
if (list.indexOf(value) > -1) {
|
||||
result = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
return formatMessage(rule, errorMessage || message['enum']);
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
|
||||
rangeNumber(rule, value, message) {
|
||||
if (!types.number(value)) {
|
||||
return formatMessage(rule, rule.errorMessage || message.pattern.mismatch);
|
||||
}
|
||||
|
||||
let {
|
||||
minimum,
|
||||
maximum,
|
||||
exclusiveMinimum,
|
||||
exclusiveMaximum
|
||||
} = rule;
|
||||
let min = exclusiveMinimum ? value <= minimum : value < minimum;
|
||||
let max = exclusiveMaximum ? value >= maximum : value > maximum;
|
||||
|
||||
if (minimum !== undefined && min) {
|
||||
return formatMessage(rule, rule.errorMessage || message['number'][exclusiveMinimum ?
|
||||
'exclusiveMinimum' : 'minimum'
|
||||
])
|
||||
} else if (maximum !== undefined && max) {
|
||||
return formatMessage(rule, rule.errorMessage || message['number'][exclusiveMaximum ?
|
||||
'exclusiveMaximum' : 'maximum'
|
||||
])
|
||||
} else if (minimum !== undefined && maximum !== undefined && (min || max)) {
|
||||
return formatMessage(rule, rule.errorMessage || message['number'].range)
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
|
||||
rangeLength(rule, value, message) {
|
||||
if (!types.string(value) && !types.array(value)) {
|
||||
return formatMessage(rule, rule.errorMessage || message.pattern.mismatch);
|
||||
}
|
||||
|
||||
let min = rule.minLength;
|
||||
let max = rule.maxLength;
|
||||
let val = value.length;
|
||||
|
||||
if (min !== undefined && val < min) {
|
||||
return formatMessage(rule, rule.errorMessage || message['length'].minLength)
|
||||
} else if (max !== undefined && val > max) {
|
||||
return formatMessage(rule, rule.errorMessage || message['length'].maxLength)
|
||||
} else if (min !== undefined && max !== undefined && (val < min || val > max)) {
|
||||
return formatMessage(rule, rule.errorMessage || message['length'].range)
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
|
||||
pattern(rule, value, message) {
|
||||
if (!types['pattern'](rule.pattern, value)) {
|
||||
return formatMessage(rule, rule.errorMessage || message.pattern.mismatch);
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
|
||||
format(rule, value, message) {
|
||||
var customTypes = Object.keys(types);
|
||||
var format = FORMAT_MAPPING[rule.format] ? FORMAT_MAPPING[rule.format] : (rule.format || rule.arrayType);
|
||||
|
||||
if (customTypes.indexOf(format) > -1) {
|
||||
if (!types[format](value)) {
|
||||
return formatMessage(rule, rule.errorMessage || message.typeError);
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
|
||||
arrayTypeFormat(rule, value, message) {
|
||||
if (!Array.isArray(value)) {
|
||||
return formatMessage(rule, rule.errorMessage || message.typeError);
|
||||
}
|
||||
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
const element = value[i];
|
||||
let formatResult = this.format(rule, element, message)
|
||||
if (formatResult !== null) {
|
||||
return formatResult
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
class SchemaValidator extends RuleValidator {
|
||||
|
||||
constructor(schema, options) {
|
||||
super(SchemaValidator.message);
|
||||
|
||||
this._schema = schema
|
||||
this._options = options || null
|
||||
}
|
||||
|
||||
updateSchema(schema) {
|
||||
this._schema = schema
|
||||
}
|
||||
|
||||
async validate(data, allData) {
|
||||
let result = this._checkFieldInSchema(data)
|
||||
if (!result) {
|
||||
result = await this.invokeValidate(data, false, allData)
|
||||
}
|
||||
return result.length ? result[0] : null
|
||||
}
|
||||
|
||||
async validateAll(data, allData) {
|
||||
let result = this._checkFieldInSchema(data)
|
||||
if (!result) {
|
||||
result = await this.invokeValidate(data, true, allData)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
async validateUpdate(data, allData) {
|
||||
let result = this._checkFieldInSchema(data)
|
||||
if (!result) {
|
||||
result = await this.invokeValidateUpdate(data, false, allData)
|
||||
}
|
||||
return result.length ? result[0] : null
|
||||
}
|
||||
|
||||
async invokeValidate(data, all, allData) {
|
||||
let result = []
|
||||
let schema = this._schema
|
||||
for (let key in schema) {
|
||||
let value = schema[key]
|
||||
let errorMessage = await this.validateRule(key, value, data[key], data, allData)
|
||||
if (errorMessage != null) {
|
||||
result.push({
|
||||
key,
|
||||
errorMessage
|
||||
})
|
||||
if (!all) break
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
async invokeValidateUpdate(data, all, allData) {
|
||||
let result = []
|
||||
for (let key in data) {
|
||||
let errorMessage = await this.validateRule(key, this._schema[key], data[key], data, allData)
|
||||
if (errorMessage != null) {
|
||||
result.push({
|
||||
key,
|
||||
errorMessage
|
||||
})
|
||||
if (!all) break
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
_checkFieldInSchema(data) {
|
||||
var keys = Object.keys(data)
|
||||
var keys2 = Object.keys(this._schema)
|
||||
if (new Set(keys.concat(keys2)).size === keys2.length) {
|
||||
return ''
|
||||
}
|
||||
|
||||
var noExistFields = keys.filter((key) => {
|
||||
return keys2.indexOf(key) < 0;
|
||||
})
|
||||
var errorMessage = formatMessage({
|
||||
field: JSON.stringify(noExistFields)
|
||||
}, SchemaValidator.message.TAG + SchemaValidator.message['defaultInvalid'])
|
||||
return [{
|
||||
key: 'invalid',
|
||||
errorMessage
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
function Message() {
|
||||
return {
|
||||
TAG: "",
|
||||
default: '验证错误',
|
||||
defaultInvalid: '提交的字段{field}在数据库中并不存在',
|
||||
validateFunction: '验证无效',
|
||||
required: '{label}必填',
|
||||
'enum': '{label}超出范围',
|
||||
timestamp: '{label}格式无效',
|
||||
whitespace: '{label}不能为空',
|
||||
typeError: '{label}类型无效',
|
||||
date: {
|
||||
format: '{label}日期{value}格式无效',
|
||||
parse: '{label}日期无法解析,{value}无效',
|
||||
invalid: '{label}日期{value}无效'
|
||||
},
|
||||
length: {
|
||||
minLength: '{label}长度不能少于{minLength}',
|
||||
maxLength: '{label}长度不能超过{maxLength}',
|
||||
range: '{label}必须介于{minLength}和{maxLength}之间'
|
||||
},
|
||||
number: {
|
||||
minimum: '{label}不能小于{minimum}',
|
||||
maximum: '{label}不能大于{maximum}',
|
||||
exclusiveMinimum: '{label}不能小于等于{minimum}',
|
||||
exclusiveMaximum: '{label}不能大于等于{maximum}',
|
||||
range: '{label}必须介于{minimum}and{maximum}之间'
|
||||
},
|
||||
pattern: {
|
||||
mismatch: '{label}格式不匹配'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
SchemaValidator.message = new Message();
|
||||
|
||||
export default SchemaValidator
|
Reference in New Issue
Block a user