vee-validate是vuejs的表单验证库,它内置了许多规则,并且支持自定义规则。
安装
1 2 3
| yarn add vee-validate
npm install vee-validate --save
|
配置
加载components并导入rules:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import Vue from 'vue' import { ValidationObserver, ValidationProvider, extend } from 'vee-validate' import * as rules from 'vee-validate/dist/rules' import { messages } from 'vee-validate/dist/locale/zh_CN.json'
Vue.component('ValidationObserver', ValidationObserver) Vue.component('ValidationProvider', ValidationProvider)
for (const [rule, validation] of Object.entries(rules)) { extend(rule, { ...validation, message: (messages as { [key: string]: string })[rule] }) }
|
Usage
具体用法参见Handling Forms,下面是两个常用例子:
Basic Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| <template> <ValidationObserver v-slot="{ invalid }"> <form @submit.prevent="onSubmit"> <ValidationProvider name="E-mail" rules="required|email" v-slot="{ errors }"> <input v-model="email" type="email"> <span>{{ errors[0] }}</span> </ValidationProvider>
<ValidationProvider name="First Name" rules="required|alpha" v-slot="{ errors }"> <input v-model="firstName" type="text"> <span>{{ errors[0] }}</span> </ValidationProvider>
<ValidationProvider name="Last Name" rules="required|alpha" v-slot="{ errors }"> <input v-model="lastName" type="text"> <span>{{ errors[0] }}</span> </ValidationProvider>
<button type="submit" :disabled="invalid">Submit</button> </form> </ValidationObserver> </template>
<script lang="ts"> export default { data: () => ({ email: '', firstName: '', lastName: '' }), methods: { onSubmit () { alert('Form has been submitted!'); } } }; </script>
<style lang="stylus" scoped> span { display: block; } </style>
|
Validate Before Submit
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| <template> <ValidationObserver v-slot="{ handleSubmit }"> <form @submit.prevent="handleSubmit(onSubmit)"> <ValidationProvider name="E-mail" rules="required|email" v-slot="{ errors }"> <input v-model="email" type="email"> <span>{{ errors[0] }}</span> </ValidationProvider>
<ValidationProvider name="First Name" rules="required|alpha" v-slot="{ errors }"> <input v-model="firstName" type="text"> <span>{{ errors[0] }}</span> </ValidationProvider>
<ValidationProvider name="Last Name" rules="required|alpha" v-slot="{ errors }"> <input v-model="lastName" type="text"> <span>{{ errors[0] }}</span> </ValidationProvider>
<button type="submit">Submit</button> </form> </ValidationObserver> </template>
<script lang="ts"> export default { data: () => ({ firstName: '', lastName: '', email: '' }), methods: { onSubmit () { alert('Form has been submitted!'); } } }; </script>
<style lang="stylus" scoped> span { display: block; } </style>
|