1、爲了方便重複利用管理,我建立一個regExp.ts文件來管理正則的表達式,內容以下:vue
1 /* eslint-disable */ 2 const phoneNumberRegExp = /^[1|9][3|4|5|6|7|8|9][0-9]\d{8}$/ 3 const passwordRegExp = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/ // 6 - 12 位字母數字組合 4 const emailRegExp = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/ 5 const idCardRegExp = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/ 6 const longitudeRegExp=/^[\-\+]?(0(\.\d{1,10})?|([1-9](\d)?)(\.\d{1,10})?|1[0-7]\d{1}(\.\d{1,10})?|180\.0{1,10})$/ //經度 7 const latitudeRegExp=/^[\-\+]?((0|([1-8]\d?))(\.\d{1,10})?|90(\.0{1,10})?)$/ //緯度 8 export { 9 phoneNumberRegExp, 10 passwordRegExp, 11 emailRegExp, 12 idCardRegExp, 13 longitudeRegExp, 14 latitudeRegExp 15 }
2、在要使用的頁面,引入上面的文件,以下:git
1 <script lang="ts"> 2 import * as api from '@/utils/api/index' 3 import { Component, Vue } from 'vue-property-decorator' 4 import eHeader from '@/components/header.vue' 5 import { constants } from 'http2' 6 import * as util from '@/utils/util.ts' //這裏就是引入的(regExp.ts)正則判斷文件,和其餘的工具類; 7 8 const testLongitude = (rule: any, value: string, callback: Function) => { 9 if (util.regExp.longitudeRegExp.test(value)) { 10 return callback() 11 } else { 12 return callback(new Error('請輸入正確的經度')) 13 } 14 } 15 const testLatitude = (rule: any, value: string, callback: Function) => { 16 if (util.regExp.latitudeRegExp.test(value)) { 17 return callback() 18 } else { 19 return callback(new Error('請輸入正確的緯度')) 20 } 21 } 22 @Component({ 23 components: { 24 'Header': eHeader 25 } 26 }) 27 export default class point extends Vue { 28 29 30 private rules = { 31 location: [ 32 { required: true, message: '請輸入接送點名稱名稱', trigger: 'blur' } 33 ], 34 longitude: [ 35 { validator: testLongitude, trigger: 'blur' } 36 ], 37 latitude: [ 38 { validator: testLatitude, trigger: 'blur' } 39 ] 40 } 41 42 mounted (){} 43 }
3、在el-form上加上 :rules="rules" ,還要在判斷的字段 el-form-item 上加上 prop="form裏的字段"api
<el-form class="inline-form" :rules="rules" ref="formData" size="small" :model="formData"> <el-form-item label="" v-if="formData.type === 1" prop="longitude"> <el-input :disabled="!ifFalg" class="my-input" clearable v-model.number="formData.longitude" placeholder="經度 " > </el-input> </el-form-item> </form>