本文实例为大家分享了vue使用element-ui实现表单验证的具体代码,供大家参考,具体内容如下
一、简单逻辑验证(直接使用rules)
实现思路
-
html中给el-form增加
:rules="rules"
-
html中在el-form-item 中增加属性
prop="名称"
- js中直接在data中定义rules:{}
html部分
1
2
3
4
5
6
|
< el-form ref = "form" :rules = "rules" :model = "form" label-width = "300px" > < el-form-item label = "发货地址:" prop = "fAdderss" > < el-input class = "inp" v-model = "form.fAdderss" auto-complete = "true" ></ el-input > < el-button type = "primary" class = "btn-add" @ click = "onSubmit" >常用地址</ el-button > </ el-form-item > </ el-form > |
js部分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<script> export default { data() { return { form: { fAdderss: '' , }, // 校验规则 rules: { fAdderss: [ { required: true , //是否必填 message: '地址不能为空' , //规则 trigger: 'blur' //何事件触发 }, //可以设置双重验证标准 { min: 3, max: 5, message: '长度在 3 到 5 个字符' , } ] } } } } </script> |
二、自定义验证逻辑
实现思路
-
html中给el-form增加
:rules="rules"
-
html中在el-form-item 中增加属性
prop="名称"
-
js中直接在data中在rules中的名称对应中设置
validator: 验证器名称,
- js中在data中 return之上书写验证器对应的js验证逻辑
html部分
1
2
3
4
5
|
< el-form ref = "form" :rules = "rules" :model = "form" label-width = "300px" > < el-form-item label = "发货人电话" prop = "phone" > < el-input class = "inp" v-model = "form.phone" auto-complete = "true" ></ el-input > </ el-form-item > </ el-form > |
js部分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<script> export default { data() { // 此处自定义校验手机号码js逻辑 var phoneReg = /^[1][3,4,5,7,8][0-9]{9}$/ var validatePhone = (rule, value, callback) => { if (!value) { return callback( new Error( '号码不能为空!!' )) } setTimeout(() => { if (!phoneReg.test(value)) { callback( new Error( '格式有误' )) } else { callback() } }, 1000) } return { form: { phone: '' , }, // 校验规则 rules: { // 校验手机号码,主要通过validator来指定验证器名称 phone: [{ required: true , validator: validatePhone, trigger: 'blur' }] }, } } } </script> |
效果图如下
三、表单提交
实现思路
-
html中给el-form增加
ref="form" :model="ruleForm"
-
html中给提交按钮增加点击事件
@click="submitForm('ruleForm')"
()中对应的为form的:model="ruleForm"
-
js中直接在methods中定义提交事件
submitForm(){}
+html部分
1
2
3
4
5
6
7
8
9
10
|
//form < el-form :model = "ruleForm" :rules = "rules" ref = "ruleForm" label-width = "0px" > //表单项 < el-form-item label = "发货人电话" prop = "phone" > < el-input class = "inp" v-model = "form.phone" auto-complete = "true" ></ el-input > </ el-form-item >、 ... //提交按钮 < el-button class = "btn-login" type = "primary" size = "medium" @ click = "submitForm('ruleForm')" >立即登录</ el-button > </ el-form > |
js部分
1
2
3
4
5
6
7
8
9
10
11
|
methods: { submitForm(formName) { this .$refs[formName].validate(valid => { if (valid) { //如果通过验证 to do... } else { console.log( 'error submit!!' ) return false } }) } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_42018790/article/details/80762149