在写业务代码时,会遇到各种需要对用户输入的数据进行校验的场景,最常见的就是表单验证,各种非空校验,正则校验等等
这里我就分享下在项目中是如何封装使用的
1. 属性介绍
参数 | 说明 | 类型 | 可选值 | 默认值 |
---|---|---|---|---|
model | 表单数据对象 | object | — | — |
rules | 表单验证规则 | object | — | — |
2. 主组件index.vue
<template>
<el-form ref="drawerRef" :model="formModel" :rules="drawerRule" class="drawer-form">
<el-form-item label="姓名" prop="mobile">
<el-input v-model.trim="formModel.mobile" size="small" maxlength="11" placeholder="请输入手机号" clearable></el-input>
</el-form-item>
</el-form>
<div class="flex flex-center-center drawer-bottom">
<el-button type="text" @click="cancel">取消</el-button>
<el-button type="primary" @click="submit">保存</el-button>
</div>
</template>
<script lang="ts">
import {Component, Vue, Prop, Watch} from 'vue-property-decorator'
import { checkPhone } from '@/utils/validate'
@Component({
name: 'xxxx',
})
export default class extends Vue {
private formModel: any = {
mobile: ''
}
private drawerRule: any = {
mobile: [
{ required: true, validator: checkPhone, trigger: 'blur' },
]
}
private cancel() {
(this.$refs.drawerRef as any).resetFields()
}
private submit() {
(this.$refs.drawerRef as any).validate(async(valid: boolean) => {
if (valid) {
// 业务代码
} else {
return false;
}
})
}
</script>
3.validate.ts
// 手机号
export const checkPhone = ( rule: any, value: any, callback: any) => {
const phoneReg = /^(?:13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{5}(\d{3}|\*{3})$/
const numReg = /^[0-9]+$/
const englishNmae = rule.field
const required = rule.required // 必填
let chineseName;
switch (englishNmae) {
case 'mobile':
chineseName = '手机号码'
break;
default:
}
if (!value && required) {
return callback(new Error(`请输入${chineseName}`))
} else if (!numReg.test(value) && required ) {
callback(new Error(`${chineseName}必须为数字`))
} else if (!phoneReg.test(value) && required ) {
callback(new Error(`请输入正确的${chineseName}格式`))
} else {
callback()
}
}
一次封装,全局使用,干净又方便