自定义规则
const checkName = (rule, value, callback) => {
const reg = /^[\w]+$/g
if (!reg.test(value)) {
callback(new Error('用户名由数字、字母组成'))
} else {
callback()
}
}
else必须要带上,不然在表单提交验证中validate()方法无法获取到结果
在rules中使用
name: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
{ min: 4, max: 8, message: '长度在 4 到 8 个字符', trigger: 'blur' },
{ validator: checkName, trigger: 'blur' }
],
模板
<el-form ref="loginForm" :rules="rules" :model="form" class="form">
<el-form-item prop="name">
<el-input prefix-icon="el-icon-user-solid" v-model="form.name"></el-input>
</el-form-item>
<el-form-item class="form_btn">
<el-button @click="subBtn()" type="primary">登录</el-button>
<el-button @click="reset">重置</el-button>
</el-form-item>
</el-form>
data () {
// 自定义验证规则
const checkName = (rule, value, callback) => {
const reg = /^[\w]+$/g
if (!reg.test(value)) {
callback(new Error('用户名由数字、字母组成'))
} else {
callback()
}
}
return {
form: {
name: '123123'
},
rules: {
name: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
{ min: 4, max: 8, message: '长度在 4 到 8 个字符', trigger: 'blur' },
{ validator: checkName, trigger: 'blur' }
]
}
}
},