使用vue3编写表单校验
时间: 2023-07-02 21:06:52 浏览: 89
vue表单自定义校验规则介绍
Vue 3 提供了更加易用和灵活的表单校验方式。以下是一个使用 Vue 3 编写表单校验的示例:
1. 在组件中定义表单数据和校验规则:
```javascript
import { defineComponent, ref } from 'vue';
export default defineComponent({
name: 'MyForm',
setup() {
const formData = ref({
username: '',
password: '',
confirmPassword: '',
email: '',
});
const rules = {
username: [
{ required: true, message: 'Username is required' },
{ min: 3, max: 10, message: 'Username length should be between 3 and 10' },
],
password: [
{ required: true, message: 'Password is required' },
{ min: 6, max: 20, message: 'Password length should be between 6 and 20' },
],
confirmPassword: [
{ required: true, message: 'Confirm password is required' },
{
validator: (rule, value) => {
if (value !== formData.value.password) {
return Promise.reject('Passwords do not match');
}
return Promise.resolve();
},
},
],
email: [
{ type: 'email', message: 'Invalid email address' },
],
};
return {
formData,
rules,
};
},
});
```
2. 在模板中绑定表单数据和校验规则:
```html
<template>
<form>
<div>
<label>Username:</label>
<input v-model="formData.username">
<div v-if="errors.username">{{ errors.username[0].message }}</div>
</div>
<div>
<label>Password:</label>
<input type="password" v-model="formData.password">
<div v-if="errors.password">{{ errors.password[0].message }}</div>
</div>
<div>
<label>Confirm Password:</label>
<input type="password" v-model="formData.confirmPassword">
<div v-if="errors.confirmPassword">{{ errors.confirmPassword[0].message }}</div>
</div>
<div>
<label>Email:</label>
<input v-model="formData.email">
<div v-if="errors.email">{{ errors.email[0].message }}</div>
</div>
<button type="submit">Submit</button>
</form>
</template>
```
3. 在组件中添加校验方法和提交方法:
```javascript
import { defineComponent, ref } from 'vue';
import { validate } from 'vee-validate';
export default defineComponent({
name: 'MyForm',
setup() {
const formData = ref({
username: '',
password: '',
confirmPassword: '',
email: '',
});
const rules = {
// ...
};
const errors = ref({});
const handleSubmit = () => {
validate(formData.value, rules, { abortEarly: false })
.then(() => {
// 校验通过,提交表单
})
.catch((err) => {
// 校验失败,显示错误信息
errors.value = err.errors;
});
};
return {
formData,
rules,
errors,
handleSubmit,
};
},
});
```
4. 在模板中绑定提交方法:
```html
<template>
<form @submit.prevent="handleSubmit">
<!-- ... -->
</form>
</template>
```
这样,就完成了一个简单的基于 Vue 3 的表单校验。你可以根据实际需求进行调整和扩展。
阅读全文