vue3 表单校验大全,含对象嵌套对象验证、数组格式验证、动态添加验证等
<template>
<Form :model="form" :rules="rules">
<FormItem label="用户名" prop="username">
<Input v-model="form.username" />
</FormItem>
<FormItem label="密码" prop="password">
<Input type="password" v-model="form.password" />
</FormItem>
<FormItem label="个人信息">
<FormItem label="年龄" prop="info.age">
<Input v-model="form.info.age" />
</FormItem>
<FormItem label="邮箱" prop="info.email">
<Input v-model="form.info.email" />
</FormItem>
</FormItem>
<FormItem label="爱好" prop="hobbies">
<CheckboxGroup v-model="form.hobbies">
<Checkbox v-for="hobby in hobbies" :key="hobby" :label="hobby"></Checkbox>
</CheckboxGroup>
</FormItem>
<FormItem>
<Button @click="submitForm">提交</Button>
</FormItem>
</Form>
</template>
<script setup>
import { reactive } from 'vue';
import { Form, FormItem, Input, CheckboxGroup, Checkbox, Button } from 'element-plus';
const form = reactive({
username: '',
password: '',
info: {
age: '',
email: ''
},
hobbies: []
});
const hobbies = ['足球', '篮球', '棋类', '编程'];
const validateAge = (rule, value, callback) => {
if (!value) {
return callback(new Error('年龄不能为空'));
}
if (!Number.isInteger(+value)) {
callback(new Error('格式不正确,应为数字值'));
} else {
callback();
}
};
const rules = {
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' }
],
'info.age': [
{ validator: validateAge, trigger: 'blur' }
],
'info.email': [
{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
],
hobbies: [
{ type: 'array', required: true, message: '请选择至少一个爱好', trigger: 'change' }
]
};
const submitForm = () => {
// 表单提交逻辑
};
</script>
这个代码实例展示了如何使用Vue 3和Element Plus创建一个包含对象嵌套对象、数组格式验证以及动态添加验证规则的表单。它使用了组合式API(<script setup>
),并通过reactive
来创建响应式数据模型,同时使用了Element Plus的Form
组件以及其它表单相关的组件如FormItem
、Input
、CheckboxGroup
和Checkbox
。代码中包含了自定义的验证规则例如对年龄的验证,以及提供了提交表单的逻辑。
评论已关闭