天天看點

element-ui中表單驗證validator統一封裝

在寫業務代碼時,會遇到各種需要對使用者輸入的資料進行校驗的場景,最常見的就是表單驗證,各種非空校驗,正則校驗等等

這裡我就分享下在項目中是如何封裝使用的

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 >
  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()
  }
}
           

一次封裝,全局使用,幹淨又友善 

繼續閱讀