Vue3 Element Plus表单自定义校验实现步骤
<template>
<el-form :model="formData" :rules="rules" ref="myForm">
<el-form-item prop="username">
<el-input v-model="formData.username"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input type="password" v-model="formData.password"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">提交</el-button>
</el-form-item>
</el-form>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
const formData = reactive({
username: '',
password: ''
});
const rules = {
username: [
{ required: true, message: '请输入用户名', trigger: 'blur' }
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' },
{ min: 6, max: 12, message: '密码长度在 6 到 12 个字符', trigger: 'blur' }
]
};
const myForm = ref(null);
const submitForm = () => {
myForm.value.validate((valid) => {
if (valid) {
ElMessage.success('提交成功');
} else {
ElMessage.error('表单验证失败');
return false;
}
});
};
</script>
这段代码展示了如何在Vue 3和Element Plus中创建一个带有自定义验证规则的表单。它定义了一个带有用户名和密码字段的表单,并且每个字段都有其对应的验证规则。当用户点击提交按钮时,会触发表单的验证,如果验证通过,会显示成功消息;如果验证失败,会显示错误消息,并阻止表单的提交。
评论已关闭