app.vuevue
<template>
<div id="app">
<el-form
:model="ruleForm"
status-icon
:rules="rules"
ref="ruleForm"
label-width="100px"
class="demo-ruleForm"
>
<el-form-item label="手機號碼" prop="phone">
<el-input v-model="ruleForm.phone" autocomplete="off"></el-input>
</el-form-item>
</el-form>
</div>
</template>
<script>
import { testMOBILE } from './validate.js'
export default {
name: 'app',
data() {
var validatePhone = (rule, value, callback) => {
if (!testMOBILE(value)) {
callback(new Error('手機號碼格式不正確'))
} else {
callback()
}
}
return {
ruleForm: {
phone: ''
},
rules: {
phone: [{ validator: validatePhone, trigger: 'change' }]
}
}
}
}
</script>
複製代碼
validate.jsbash
export const testMOBILE = (val, reg) => {
!reg && (reg = /^1(3|4|5|6|7|8|9)\d{9}$/)
return res(reg, val)
}
const res = (reg, val) => {
if (!reg || !val) return false
if (reg.test(val)) return true
return false
}
複製代碼