vue3 表单验证规则
时间: 2023-12-23 22:28:34 浏览: 111
表单验证方法
以下是Vue3中的表单验证规则的示例:
```javascript
import { ref, reactive } from 'vue';
import { FormInstance, FormRules } from 'element-plus';
// 创建表单实例
const ruleFormRef = ref<FormInstance>();
// 表单数据对象
const ruleForm = reactive({
userId: "",
email: "test@qq.com",
pwd1: "",
pwd2: "",
});
// 校验规则
const rules = reactive<FormRules>({
userId: [
{ required: true, message: '请输入用户ID', trigger: 'blur' },
{ min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
],
email: [
{ required: true, message: '请输入邮箱', trigger: 'blur' },
{ type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
],
pwd1: [
{ required: true, message: '请输入密码', trigger: 'blur' },
{ min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
],
pwd2: [
{ required: true, message: '请再次输入密码', trigger: 'blur' },
{ validator: (rule, value, callback) => {
if (value !== ruleForm.pwd1) {
callback(new Error('两次输入密码不一致'));
} else {
callback();
}
}, trigger: 'blur'
}
]
});
// 在模板中使用表单和规则
<template>
<el-form :model="ruleForm" :rules="rules" ref="ruleFormRef">
<el-form-item label="用户ID" prop="userId">
<el-input v-model="ruleForm.userId"></el-input>
</el-form-item>
<el-form-item label="邮箱" prop="email">
<el-input v-model="ruleForm.email"></el-input>
</el-form-item>
<el-form-item label="密码" prop="pwd1">
<el-input type="password" v-model="ruleForm.pwd1"></el-input>
</el-form-item>
<el-form-item label="确认密码" prop="pwd2">
<el-input type="password" v-model="ruleForm.pwd2"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">提交</el-button>
</el-form-item>
</el-form>
</template>
// 提交表单
const submitForm = () => {
ruleFormRef.value.validate((valid) => {
if (valid) {
// 表单验证通过,执行提交操作
// ...
} else {
// 表单验证失败,进行错误处理
// ...
}
});
};
```
阅读全文