element-ui 给el-form表单添加校验规则
<!-- 对话框组件 :visible.sync(设置是否显示对话框) width(设置对话框的宽度)
:before-close(在对话框关闭前触发的事件) -->
<el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%">
<!-- 对话框主体区域 -->
<el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
<el-form-item label="用户名" prop="username">
<el-input v-model="addForm.username"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="addForm.password"></el-input>
</el-form-item>
<el-form-item label="邮箱" prop="email">
<el-input v-model="addForm.email"></el-input>
</el-form-item>
<el-form-item label="电话" prop="mobile">
<el-input v-model="addForm.mobile"></el-input>
</el-form-item>
</el-form>
<!-- 对话框底部区域 -->
<span slot="footer" class="dialog-footer">
<el-button @click="addDialogVisible = false">取 消</el-button>
<el-button type="primary" @click="addDialogVisible = false">确 定</el-button>
</span>
</el-dialog>
校验规则
data(){
//验证邮箱的规则
var checkEmail = (rule, value, cb) => {
const regEmail = /^\[email protected]\w+(\.\w+)+$/
if (regEmail.test(value)) {
return cb()
}
//返回一个错误提示
cb(new Error(‘请输入合法的邮箱‘))
}
//验证手机号码的规则
var checkMobile = (rule, value, cb) => {
const regMobile = /^1[34578]\d{9}$/
if (regMobile.test(value)) {
return cb()
}
//返回一个错误提示
cb(new Error(‘请输入合法的手机号码‘))
}
return {
...
addDialogVisible: false, // 控制添加用户对话框的显示与隐藏
// 添加用户的表单数据
addForm: {
username: ‘‘,
password: ‘‘,
email: ‘‘,
mobile: ‘‘
},
// 添加表单的验证规则对象
addFormRules: {
username: [
{ required: true, message: ‘请输入用户名称‘, trigger: ‘blur‘ },
{
min: 3,
max: 10,
message: ‘用户名在3~10个字符之间‘,
trigger: ‘blur‘
}
],
password: [
{ required: true, message: ‘请输入密码‘, trigger: ‘blur‘ },
{
min: 6,
max: 15,
message: ‘用户名在6~15个字符之间‘,
trigger: ‘blur‘
}
],
email: [
{ required: true, message: ‘请输入邮箱‘, trigger: ‘blur‘ },
{ validator:checkEmail, message: ‘邮箱格式不正确,请重新输入‘, trigger: ‘blur‘}
],
mobile: [
{ required: true, message: ‘请输入手机号码‘, trigger: ‘blur‘ },
{ validator:checkMobile, message: ‘手机号码不正确,请重新输入‘, trigger: ‘blur‘}
]
}
}
关闭对话框后将表单清空,否则下次打开表单会有数据在里面
addDialogClosed(){
//对话框关闭之后,重置表达
this.$refs.addFormRef.resetFields();
}
原文地址:https://www.cnblogs.com/YangxCNWeb/p/12608878.html
时间: 2024-10-10 20:27:02