- 本地注册或全局注册由使用频率决定
- src/includes/validation.js (自定义插件)
为什么平台的表单验证要在客户端进行
- 立即反馈
- 进行表单验证减少对服务器的请求
使用第三方库完成表单验证
1.下载
npm i vee-validate
2. 注册(需要操作两个文件)
// src/includes/validation.js
import { Form as VeeForm, Field as VeeField } from "vee-validate";
export default {
install(app) {
app.component("VeeForm", VeeForm);
app.component("VeeField", VeeField);
},
};
// main.js
import VeeValidatePlugin from "./includes/validation";
app.use(VeeValidatePlugin);
3.使用
1.使用组件
// auth.vue
// - 未替换时
<form>
<input />
</form>
// - 替换后
// 全局注册时组件名称为 VeeForm, VeeField
<vee-form>
<vee-field></vee-field>
</vee-form>
2.分配一个名字给 input
// auth.vue
<vee-form>
<vee-field name="name"></vee-field>
</vee-form>
- 定义规则
- 下载规则
npm i @validate/rules
- 定义规则
// src/includes/validation.js
//defineRule 允许我们全局定义规则
import { Form as VeeForm, Field as VeeField, defineRule } from "vee-validate"; // +
import { required } from "@vee-validate/rules"; // +
export default {
install(app) {
app.component("VeeForm", VeeForm);
app.component("VeeField", VeeField);
defineRule("required", required); // +
},
};
- 使用规则
- 未优化版
// auth.vue
// + :rules="required"
<vee-form>
<vee-field name="name" :rules="'required'"></vee-field>
</vee-form>
- 优化版 : 保持模板干净
// auth.vue
// - :rules="required"
// schema 是包含这些规则的对象
<vee-form :validation-schema="schema"> {/* + */}
<vee-field name="name" ></vee-field>
</vee-form>
// 将下面schma对象添加到data
schema: {
name: 'required',
email: '',
age: '',
password: '',
confirm_password: '',
country: '',
tos: ''
}
- 错误处理
- 注册错误处理组件
// src/includes/validation.js
import { Form as VeeForm, Field as VeeField, ErrorMessage } from "vee-validate"; // +
export default {
install(app) {
app.component("VeeForm", VeeForm);
app.component("VeeField", VeeField);
app.component("ErrorMessage", ErrorMessage); // +
defineRule("required", required);
},
};
使用错误处理组件
<ErrorMessage class="text-red-600" name="name" />
- 添加更多规则
// src/includes/validation.js
import {
Form as VeeForm,
Field as VeeField,
defineRule,
ErrorMessage,
} from "vee-validate";
import {
required,
min,
max,
alpha_spaces as alphaSpaces,
} from "@vee-validate/rules"; // +
export default {
install(app) {
app.component("VeeForm", VeeForm);
app.component("VeeField", VeeField);
app.component("ErrorMessage", ErrorMessage);
defineRule("required", required);
defineRule("min", min); // +
defineRule("max", max); // +
defineRule("alphaSpaces", alphaSpaces); // +
},
};
//auth.vue
// 为name添加规则
schema: {
name: 'required|min:3|max:100|alphaSpaces',// +
email: '',
age: '',
password: '',
confirm_password: '',
country: '',
tos: ''
}
评论 (0)