使用 Vue.js 和 Vuelidate 进行基于模型的表单验证

虽然在 Vue.js 中对表单验证的最初学者友好的方法可能是通过基于模板的表单,但更灵活的方法是验证模型。 基于模型的验证往往更容易理解和更改大型应用程序,将视觉混乱从模板移动到模型并大大缩小。

安装

像往常一样,Vuelidate可以从NPM或Yarn安装。

1# Yarn
2$ yarn add vuelidate
3
4# NPM
5$ npm install vuelidate --save

然后,在您的应用程序 bootstrap 中,启用Vuelidate插件。

 1[label main.js]
 2import Vue from 'vue';
 3import Vuelidate from 'vuelidate';
 4import App from 'App.vue';
 5
 6Vue.use(Vuelidate);
 7
 8new Vue({
 9  el: '#app',
10  render: h => h(App)
11});

现场验证

若要验证字段,请将数据模型中的属性定义对象添加到组件的验证属性中,然后从 vuelidate/lib/validations (或您创建的自定义函数) 导入验证函数。

$v 的計劃:

1$v[propertyName]: {
2  $dirty: boolean, // Whether or not this field has been interacted with yet.
3  $invalid: boolean, // If this field is current valid or invalid, regardless of whether or not it is "dirty"
4  $error: boolean, // Shortcut for $invalid && $dirty
5  $pending: boolean, // Whether or not there is a pending validation (for async validations)
6  $each: object // Holds all the validations for looped models.
7  [YourValidationName]: boolean // The state of the validations defined on this property validations. (ie. if you have the 'required' validator, there would be a boolean 'required' property here, and so forth.)
8  [Nested]: object // You can nest values in your model here as well, and the validation properties will be added to each nested field.
9}
 1<template>
 2  <form>
 3    <input type="text" v-model="emailValue"/>
 4    <p v-if="!$v.emailValue.required">The email field is required!</p>
 5    <p v-if="!$v.emailValue.email">The input must be a proper email!</p>
 6  </form>
 7</template>
 8
 9<script>
10import { required, email } from 'vuelidate/lib/validations'
11
12export default {
13  data() {
14    return {
15      emailValue: ''
16    }
17  },
18
19  validations: {
20    emailValue: {
21      required,
22      email
23    }
24  }
25}
26</script>

内置验证器

Vuelidate 默认情况下提供这些验证器. 它们可以从 vuelidate/lib/validators 中导入。 如果您使用 Webpack 2 或 Rollup 与树木摇动,在您的项目中未使用的任何验证器将不会与其结合。

  • required() - 此字段不能空.
  • minLength(长度:数字) - 字段的最小长度. 工作在字符串和序列
  • maxLength(长度:数字) - 字段的最大长度. 工作在字符串和序列 *之间(min, max) - 只允许有效的电子邮件 之间的数值
  • alpha() - 只允许字母字符
  • alphaNum() - 只允许字符串和序列 电子邮件() - 允许只有有效的电子邮件

定制验证器

Vuelidate 中的自定义验证器只是一个函数,该函数返回一个布尔式或一个解决一个布尔式的承诺。

如果您想确保字段只包含空格这个词,您可以写一个类似于此的验证器。

1[label tom-validator.js]
2export const TomValidator = (value, component) => {
3  return value === 'tom';
4}
 1[label MyComponent.vue]
 2...
 3<script>
 4import { TomValidator } from './tom-validator';
 5export default {
 6  data() {
 7    return {
 8      inputField: ''
 9    }
10  },
11
12  validators: {
13    inputField: {
14      TomValidator
15    }
16  }
17}
18</script>

您可能想更进一步,并允许指定必须匹配的字符串,在这种情况下,只需创建一个更高顺序的函数,该函数返回验证函数。

1[label match-validator.js]
2export const MatchValidator = (stringToMatch) => {
3  return (value, component) => value === stringToMatch;
4}
 1[label MyComponent.vue]
 2...
 3<script>
 4import { MatchValidator } from './match-validator';
 5export default {
 6  data() {
 7    return {
 8      inputField: ''
 9    }
10  },
11
12  validators: {
13    inputField: {
14      MatchValidator: MatchValidator('rupert')
15      // Only allows inputField to contain 'rupert.' One might Wonder why the field even exists then...
16    }
17  }
18}
19</script>
Published At
Categories with 技术
Tagged with
comments powered by Disqus