select some api

This commit is contained in:
2026-04-15 18:11:27 +08:00
commit bab2a78f73
372 changed files with 47483 additions and 0 deletions

View File

@@ -0,0 +1,450 @@
<template>
<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 v-if="label" class="uni-forms-item__label" :style="{width:labelWid+'px',justifyContent: justifyContent}">
<slot name="left">
<uni-icons v-if="leftIcon" class="label-icon" size="16" :type="leftIcon" :color="iconColor" />
<text class="label-text">{{label}}</text>
<text v-if="required" class="is-required">*</text>
</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: (labelPos === 'left'? Number(labelWid)+5:5) + 'px'
}"><text class="uni-error-message-text">{{ showMsg === 'undertext' ? msg:'' }}</text></view>
</view>
</view>
</template>
<script>
/**
* FormsItem 表单子组件
* @description 此组件可以实现表单的输入与校验,包括 "text" 和 "textarea" 类型。
* @tutorial https://ext.dcloud.net.cn/plugin?id=2773
* @property {String} name 表单域的属性名,在使用校验规则时必填
* @property {Boolean} required 左边显示红色"*"号,样式显示不会对校验规则产生效果(默认 false
* @property {String} validate-trigger = [bind|submit] 表单校验时机(默认 submit
* @value bind 数据发生变化时触发
* @value submit 提交表单是触发
* @property {String} left-icon label左边的图标限uni-ui的图标名称
* @property {String} icon-color 左边通过icon配置的图标的颜色 (默认 #606266
* @property {String} label 输入框左边的文字提示
* @property {Number} label-width label的宽度单位px
* @property {String} label-align = [left|center|right] label的文字对齐方式默认 left
* @value left 左对齐
* @value center 居中对齐
* @value right 右对齐
* @property {String} label-position = [top|left] label的文字的位置默认 left
* @value top 顶部显示 label
* @value left 左侧显示 label
* @property {String} error-message 显示的错误提示内容如果为空字符串或者false则不显示错误信息
*/
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: ''
}
},
data() {
return {
errorTop: false,
errorBottom: false,
labelMarginBottom: '',
errorWidth: '',
errMsg: '',
val: '',
labelPos: '',
labelWid: '',
labelAli: '',
showMsg: 'undertext',
border: false,
isFirstBorder: false
};
},
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';
}
},
watch: {
validateTrigger(trigger) {
this.formTrigger = trigger
}
},
created() {
this.form = this.getForm()
this.group = this.getForm('uniGroup')
this.formRules = []
this.formTrigger = this.validateTrigger
if (this.form) {
this.form.childrens.push(this)
}
this.init()
},
destroyed() {
if (this.form) {
this.form.childrens.forEach((item, index) => {
if (item === this) {
this.form.childrens.splice(index, 1)
delete this.form.formData[item.name]
}
})
}
},
methods: {
init() {
if (this.form) {
let {
formRules,
validator,
formData,
value,
labelPosition,
labelWidth,
labelAlign,
errShowType
} = this.form
this.labelPos = this.labelPosition ? this.labelPosition : labelPosition
this.labelWid = this.label ? (this.labelWidth ? this.labelWidth : labelWidth):0
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
if (formRules) {
this.formRules = formRules[this.name] || {}
}
this.validator = validator
} else {
this.labelPos = this.labelPosition || 'left'
this.labelWid = this.labelWidth || 65
this.labelAli = this.labelAlign || 'left'
}
},
/**
* 获取父元素实例
*/
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 = ''
},
setValue(value){
if (this.name) {
if(this.errMsg) this.errMsg = ''
this.form.formData[this.name] = this.form._getValue(this.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, callback) {
let promise = null;
this.errMsg = ''
// if no callback, return promise
// if (callback && typeof callback !== 'function' && Promise) {
// promise = new Promise((resolve, reject) => {
// callback = function(valid) {
// !valid ? resolve(valid) : reject(valid)
// };
// });
// }
// if (!this.validator) {
// typeof callback === 'function' && callback(null);
// if (promise) return promise
// }
if (!this.validator) 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)) {
result = await this.validator.validateUpdate({
[this.name]: value
}, this.form.formData)
}
// 判断是否必填,非必填,不填不校验,填写才校验
if (!isNoField && (value === undefined || value === '')) {
result = null
}
if (isTrigger && result && result.errorMessage) {
const inputComp = this.form.inputChildrens.find(child => child.rename === this.name)
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 || '校验错误'
})
}
}
this.errMsg = !result ? '' : result.errorMessage
// 触发validate事件
this.form.validateCheck(result ? result : null)
// typeof callback === 'function' && callback(result ? result : null);
// if (promise) return promise
},
/**
* 触发时机
* @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" scoped>
.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: 36px;
margin-right: 5px;
.label-text {
font-size: 14px;
color: #333;
}
}
.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;
}
.uni-error-message {
position: absolute;
bottom: 0px;
left: 0;
text-align: left;
}
.uni-error-message-text {
line-height: 22px;
color: $uni-color-error;
font-size: 12px;
}
.uni-error-msg--boeder {
position: relative;
bottom: 0;
line-height: 22px;
}
.is-input-error-border {
border-color: $uni-color-error;
}
.uni-forms-item--border {
margin-bottom: 0;
padding: 10px 0;
// padding-bottom: 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 */
}
</style>

View File

@@ -0,0 +1,457 @@
<template>
<!-- -->
<view class="uni-forms" :class="{'uni-forms--top':!border}">
<form @submit.stop="submitForm" @reset="resetForm">
<slot></slot>
</form>
</view>
</template>
<script>
import Vue from 'vue'
import Validator from './validate.js'
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)
}
}
/**
* 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',
props: {
value: {
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: 65
},
// label 居中方式,可选值 left/center/right
labelAlign: {
type: String,
default: 'left'
},
errShowType: {
type: String,
default: 'undertext'
},
border: {
type: Boolean,
default: false
}
},
data() {
return {
formData: {}
};
},
watch: {
rules(newVal) {
this.init(newVal)
},
trigger(trigger) {
this.formTrigger = trigger
},
},
created() {
let _this = this
this.childrens = []
this.inputChildrens = []
this.checkboxChildrens = []
this.formRules = []
// this.init(this.rules)
},
mounted() {
this.init(this.rules)
},
methods: {
init(formRules) {
// 判断是否有规则
if (Object.keys(formRules).length > 0) {
this.formTrigger = this.trigger
this.formRules = formRules
// if (!this.validator) {
this.validator = new Validator(formRules)
// }
} else {
return
}
// 判断表单存在那些实例
for (let i in this.value) {
const itemData = this.childrens.find(v => v.name === i)
if (itemData) {
this.formData[i] = this.value[i]
itemData.init()
}
}
// watch 每个属性 ,需要知道具体那个属性发变化
Object.keys(this.value).forEach((key) => {
this.$watch('value.' + key, (newVal) => {
const itemData = this.childrens.find(v => v.name === key)
if (itemData) {
this.formData[key] = this._getValue(key, newVal)
itemData.init()
} else {
this.formData[key] = this.value[key] || null
}
})
})
},
/**
* 设置校验规则
* @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
this.$emit('input', Object.assign({}, this.value, this.formData))
return example.triggerCheck(value, callback)
},
/**
* TODO 表单提交, 小程序暂不支持这种用法
* @param {Object} event
*/
submitForm(event) {
const value = event.detail.value
return this.validateAll(value || this.formData, 'submit')
},
/**
* 表单重置
* @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 = ''
inputComp.$emit('input', inputComp.multiple ? [] : '')
}
})
this.childrens.forEach((item) => {
if (item.name) {
this.formData[item.name] = this._getValue(item.name, '')
}
})
this.$emit('input', this.formData)
this.$emit('reset', event)
},
/**
* 触发表单校验,通过 @validate 获取
* @param {Object} validate
*/
validateCheck(validate) {
if (validate === null) validate = null
this.$emit('validate', validate)
},
/**
* 校验所有或者部分表单
*/
async validateAll(invalidFields, type, callback) {
this.childrens.forEach(item => {
item.errMsg = ''
})
let promise;
if (!callback && typeof callback !== 'function' && Promise) {
promise = new Promise((resolve, reject) => {
callback = function(valid, invalidFields) {
!valid ? resolve(invalidFields) : reject(valid);
};
});
}
let fieldsValue = {}
let tempInvalidFields = Object.assign({}, invalidFields)
Object.keys(this.formRules).forEach(item => {
const values = this.formRules[item]
const rules = (values && values.rules) || []
let isNoField = false
for (let i = 0; i < rules.length; i++) {
const rule = rules[i]
if (rule.required) {
isNoField = true
break
}
}
// 如果存在 required 才会将内容插入校验对象
if (!isNoField &&
((tempInvalidFields[item] === undefined ||
tempInvalidFields[item] === '') &&
tempInvalidFields[item] !== false
)) {
delete tempInvalidFields[item]
}
})
// 循环字段是否存在于校验规则中
for (let i in this.formRules) {
for (let j in tempInvalidFields) {
const index = this.childrens.findIndex(v => v.name === j)
if (i === j && index !== -1) {
fieldsValue[i] = tempInvalidFields[i]
}
}
}
let result = []
let example = null
let newFormData = {}
this.childrens.forEach(v => {
newFormData[v.name] = this._getValue(v.name, invalidFields[v.name])
})
if (this.validator) {
for (let i in fieldsValue) {
// 循环校验,目的是异步校验
const resultData = await this.validator.validateUpdate({
[i]: fieldsValue[i]
}, this.formData)
// 未通过
if (resultData) {
// 获取当前未通过子组件实例
example = this.childrens.find(child => child.name === resultData.key)
// 获取easyInput 组件实例
const inputComp = this.inputChildrens.find(child => child.rename === (example && example
.name))
if (inputComp) {
inputComp.errMsg = resultData.errorMessage
}
result.push(resultData)
// 区分触发类型
if (this.errShowType === 'undertext') {
if (example) example.errMsg = resultData.errorMessage
} else {
if (this.errShowType === 'toast') {
uni.showToast({
title: resultData.errorMessage || '校验错误',
icon: 'none'
})
break
} else if (this.errShowType === 'modal') {
uni.showModal({
title: '提示',
content: resultData.errorMessage || '校验错误'
})
break
} else {
if (example) example.errMsg = resultData.errorMessage
}
}
}
}
}
if (Array.isArray(result)) {
if (result.length === 0) result = null
}
if (type === 'submit') {
this.$emit('submit', {
detail: {
value: newFormData,
errors: result
}
})
} else {
this.$emit('validate', result)
}
callback && typeof callback === 'function' && callback(result, newFormData)
if (promise && callback) {
return promise
} else {
return null
}
},
/**
* 外部调用方法
* 手动提交校验表单
* 对整个表单进行校验的方法,参数为一个回调函数。
*/
submit(callback) {
// Object.assign(this.formData,formData)
for (let i in this.value) {
const itemData = this.childrens.find(v => v.name === i)
if (itemData) {
if (this.formData[i] === undefined) {
this.formData[i] = this._getValue(i, this.value[i])
}
}
}
return this.validateAll(this.formData, 'submit', callback)
},
/**
* 外部调用方法
* 校验表单
* 对整个表单进行校验的方法,参数为一个回调函数。
*/
validate(callback) {
return this.validateAll(this.formData, '', callback)
},
/**
* 部分表单校验
* @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, '', 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" scoped>
.uni-forms {
// overflow: hidden;
// padding: 10px 15px;
}
.uni-forms--top {
// padding: 10px 15px;
// padding-top: 22px;
}
</style>

View File

@@ -0,0 +1,472 @@
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) {
// TODO
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 || rule.minimum) {
result = 'rangeNumber'
} else if (rule.maxLength || rule.minLength) {
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