Vue2-ElmentUI 表单数据验证

开始

一定要设置el-form标签的modelrulesref属性和el-form-itemprop属性

  • model:表单的数据对象
  • rules:表单的验证规则
  • ref:用来给表单命名的

案例代码如下:

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<template>
<!-- 密码编辑框 -->
<el-dialog
title="修改密码"
:visible.sync="dialogVisibleEdit"
width="30%">

<el-form :model="passwordEdit"
:rules="formRules"
ref="passwordEdit">
<el-form-item prop="password">
<el-input v-model="passwordEdit.password" show-password placeholder="请输入新密码"/>
</el-form-item>
<el-form-item prop="password">
<el-input v-model="passwordEdit.passwordRepeat" show-password placeholder="请重复密码"/>
</el-form-item>
</el-form>

<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisibleEdit = false">取 消</el-button>
<el-button type="primary" @click="editPassword('passwordEdit')">确 定</el-button>
</span>
</el-dialog>
</template>

<script>
export default {
components: {
Dialog
},
data() {
return {
// 表单验证规则
formRules: {
password: [
{ required: true, message: '请输入密码', trigger: 'blur' },
{ pattern: /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_]).{6,24}$/, message: '至少包含数字、字母和特殊字符,长度在6到24位之间', trigger: 'blur' }
],
},
passwordEdit: {
password: '', // 密码
passwordRepeat: '', // 重复密码
},
dialogVisibleEdit: false, // 编辑框的显示
};
},
methods: {
// 修改密码
editPassword(formName) {
// 验证表单
this.$refs[formName].validate((valid) => {
if (valid) {
// 成功逻辑
this.$notify.success({
title: '成功',
message: '密码修改成功,请重新登录!'
})
} else {
// 失败逻辑
this.$notify.error({
title: '错误',
message: '请按要求填写表单',
})
}
})
},
}
}
</script>

参考文章

ElmentUI表单验证