Vue.js 2.2的全面表单验证

语言形式 (vue-form)

Form validation for Vue.js 2.2+

Vue.js 2.2的表单验证

现场例子 (Live examples)

安装 (Install)

Available through npm as vue-form.

通过npm作为vue-form可用。

import VueForm from 'vue-form';
// or var VueForm = require('vue-form') or window.VueForm if you are linking directly to the dist file

// install globally
Vue.use(VueForm);
Vue.use(VueForm, options);

// or use the mixin
...
mixins: [VueForm]
...
mixins: [new VueForm(options)]
...

用法 (Usage)

Once installed you have access to four components (vue-form, validate, field, field-messages) for managing form state, validating form fields and displaying validation messages.

安装后,您可以访问四个组件( vue-formvalidatefieldfield-messages )来管理表单状态,验证表单字段和显示验证消息。

Example

<div id="app">
  <vue-form :state="formstate" @submit.prevent="onSubmit">

    <validate tag="label">
      <span>Name *</span>
      <input v-model="model.name" required name="name" />

      <field-messages name="name">
        <div>Success!</div>
        <div slot="required">Name is a required field</div>
      </field-messages>
    </validate>

    <validate tag="label">
      <span>Email</span>
      <input v-model="model.email" name="email" type="email" required />

      <field-messages name="email">
        <div slot="required">Email is a required field</div>
        <div slot="email">Email is not valid</div>
      </field-messages>
    </validate>

    <button type="submit">Submit</button>
  </vue-form>
  <pre>{{ formstate }}</pre>
</div>
Vue.use(VueForm);

new Vue({
  el: '#app',
  data: {
    formstate: {},
    model: {
      name: '',
      email: 'invalid-email'
    }
  },
  methods: {
    onSubmit: function () {
      if(this.formstate.$invalid) {
        // alert user and exit early
        return;
      }
      // otherwise submit form
    }
  }
});

The output of formstate will be:

formstate的输出将是:

{
  "$dirty": false,
  "$pristine": true,
  "$valid": false,
  "$invalid": true,
  "$submitted": false,
  "$touched": false,
  "$untouched": true,
  "$pending": false,
  "$error": {
    // fields with errors are copied into this object
  },
  "$submittedState": {
    // each form sumbit, state is cloned into this object
  },
  "name": {
    "$name": "name",
    "$dirty": false,
    "$pristine": true,
    "$valid": false,
    "$invalid": true,
    "$touched": false,
    "$untouched": true,
    "$pending": false,
    "$error": {
      "required": true
    }
  },
  "email": {
    "$name": "email",
    "$dirty": false,
    "$pristine": true,
    "$valid": false,
    "$invalid": true,
    "$touched": false,
    "$untouched": true,
    "$pending": false,
    "$error": {
      "email": true
    }
  }
}

显示讯息 (Displaying messages)

Display validation errors or success messages with field-messages.

使用field-messages显示验证错误或成功field-messages

The show prop supports simple expressions which specifiy when messages should be displayed based on the current state of the field, e.g: $dirty, $dirty && $touched, $dirty || $touched, $touched || $submitted

show prop支持简单的表达式,这些表达式根据字段的当前状态指定何时显示消息,例如: $dirty$dirty && $touched$dirty || $touched $dirty || $touched$touched || $submitted $touched || $submitted

<field-messages name="name" show="$dirty && $touched">
  <div slot="errorKeyA">Error message A</div>
  <div slot="errorKeyB">Error message B</div>
</field-messages>

Or use scoped templates:

或使用范围模板:

<field-messages name="fieldName">
  <span>Success</span>
  <template slot="required" scope="state">
    <span v-if="state.$touched || state.$submitted">Name is a required field</span>
  </template>
  <template slot="errorKeyB" scope="state">
    <span v-if="state.$touched || state.$dirty">Error message B</span>
  </template>
</field-messages>

验证者 (Validators)

type="email"
type="url"
type="number"
required
minlength
maxlength
pattern
min (for type="number")
max (for type="number")

You can use static validation attributes or bindings. If it is a binding, the input will be re-validated every binding update meaning you can have inputs which are conditionally required etc.

您可以使用静态验证属性或绑定。 如果是绑定,则每次绑定更新时将重新验证输入,这意味着您可以输入有条件要求的输入等。

<!-- static validators -->
<validate>
  <input type="email" name="email" v-model="model.email" required />
</validate>
<validate>
  <input type="text" name="name" v-model="model.name" maxlength="25" minlength="5" />
</validate>

<!-- bound validators -->
<validate>
  <input type="email" name="email" v-model="model.email" :required="isRequired" />
</validate>
<validate>
  <input type="text" name="name" v-model="model.name" :maxlength="maxLen" :minlength="minLen" />
</validate>
定制验证器 (Custom validators)

You can register global and local custom validators.

您可以注册全局和本地自定义验证器。

Global custom validator

全局自定义验证器

var options = {
  validators: {
    'my-custom-validator': function (value, attrValue, vnode) {
      // return true to set input as $valid, false to set as $invalid
      return value === 'custom';
    }
  }
}

Vue.use(VueForm, options);
// or
// mixins: [new VueForm(options)]
<validate>
  <input v-model="something" name="something" my-custom-validator />
  <!--
    slot name inside field-messages would be: <div slot="my-custom-validator">...</div>
  -->
</validate>

Local custom validator

本地自定义验证器

// ...
methods: {
  customValidator: function (value) {
    // return true to set input as $valid, false to set as $invalid
    return value === 'custom';
  }
},
// local custom validator can also be a data or computed property
computed: {
  isEmailAvailable function () {
    // return true to set input as $valid, false to set as $invalid
  }
}
// ...
<validate :custom="{customValidator: customValidator, 'email-available': isEmailAvailable}">
  <input v-model="something" name="something" />
  <!--
    slot name inside field-messages would be: <div slot="customValidator">...</div>
  -->
</validate>
异步验证器: (Async validators:)

Async validators are custom validators which return a Promise. resolve() true or false to set field validity.

异步验证器是返回Promise的自定义验证器。 resolve() truefalse设置字段有效性。

// ...
methods: {
  customValidator (value) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(value === 'ajax');
      }, 100);
    });
  }
}
// ...

Async validator with debounce (example uses lodash debounce)

带有反跳的异步验证器(示例使用lodash反跳)

methods: {
  debounced: _.debounce(function (value, resolve, reject) {
    fetch('https://httpbin.org/get').then(function(response){
      resolve(response.isValid);
    });
  }, 500),
  customValidator (value) {
    return new Promise((resolve, reject) => {
      this.debounced(value, resolve, reject);
    });
  }
}

重置状态 (Reset state)

<vue-form ref="form" :state="formstate">

resetState: function () {
  this.formstate._reset();
  // or
  this.$refs.form.reset();
}

州级 (State classes)

As form and input validation states change, state classes are added and removed

随着表单和输入验证状态的更改,添加和删除状态类

Possible form classes:

可能的表格类别:

vf-form-dirty, vf-form-pristine, vf-form-valid, vf-form-invalid, vf-form-submitted

Possible input classes:

可能的输入类别:

vf-dirty, vf-pristine, vf-valid, vf-invalid

// also for every validation error, a class will be added, e.g.
vf-invalid-required, vf-invalid-minlength, vf-invalid-max, etc

Input wrappers (e.g. the tag the validate component renders) will also get state classes, but with the field prefix, e.g.

输入包装器(例如validate组件渲染的标签)也将获得状态类,但带有field前缀,例如

vf-field-dirty, vf-field-pristine, vf-field-valid, vf-field-invalid

定制组件 (Custom components)

When writing custom form field components, e.g. <my-checkbox v-model="foo"></my-checkbox> you should trigger the focus and blur events after user interaction either by triggering native dom events on the root node of your component, or emitting Vue events (this.$emit('focus)) so the validate component can detect and set the $dirty and $touched states on the field.

在编写自定义表单字段组件时,例如<my-checkbox v-model="foo"></my-checkbox>您应该在用户交互后触发focusblur事件,方法是在组件的根节点上触发本机dom事件,或发出Vue事件( this.$emit('focus) ),以便validate组件可以检测并设置字段上的$dirty$touched状态。

组件道具 (Component props)

语言形式 (vue-form)
  • state Object on which form state is set

    state设置表单状态的对象

  • tag String, defaults to form

    tag字符串,默认为form

  • show-messages String, applies to all child field-messages, show errors dependant on form field state e.g. $touched, $dirty || $touched, '$touched || $submitted'

    show-messages字符串,适用于所有子field-messages ,显示取决于表单字段状态的错误,例如$touched$dirty || $touched $dirty || $touched ,'$ touched || $ submitted'

验证 (validate)
  • state Optional way of passing in the form state. If omitted form state will be found in the $parent

    state传递表单状态的可选方式。 如果省略,则会在$ parent中找到状态

  • custom Object containing one or many custom validators. {validatorName: validatorFunction}

    custom对象,包含一个或多个自定义验证器。 {validatorName: validatorFunction}

  • tag String which specifies what element tag should be rendered by the validate component, defaults to span

    tag字符串,它指定validate组件应呈现的元素标签,默认为span

  • auto-label: Boolean, defaults to false. Automatically set for and id attributes of label and input elements found inside the validate component

    auto-label :布尔值,默认为false。 自动设定forid标签的属性和输入元件中发现的内部validate部件

  • debounce Number, defaults to none, which specifies the delay (milliseconds) before validation takes place.

    debounce Number,默认为none,它指定验证发生之前的延迟(毫秒)。

现场消息 (field-messages)
  • state Optional way of passing in the form state. If omitted form state will be found in the $parent

    state传递表单状态的可选方式。 如果省略,则会在$ parent中找到状态

  • name String which specifies the related field name

    name字符串,它指定相关的字段名称

  • tag String, defaults to div

    tag字符串,默认为div

  • show String, show error dependant on form field state e.g. $touched, $dirty || $touched, '$touched || $submitted'

    show String,根据表单字段状态显示错误,例如$touched$dirty || $touched $dirty || $touched ,'$ touched || $ submitted'

  • auto-label Boolean, defaults to false. Automatically set the for attribute of labels found inside the field-messages component

    auto-label布尔值,默认为false。 自动设置在field-messages组件内找到的标签的for属性

领域 (field)
  • tag String, defaults to div

    tag字符串,默认为div

  • auto-label Boolean, defaults to true. Automatically set for and id attributes of label and input elements found inside the validate component

    auto-label布尔值,默认为true。 自动设定forid标签的属性和输入元件中发现的内部validate部件

设定档 (Config)

Set config options when using Vue.use(VueForm, options), or when using a mixin mixins: [new VueForm(options)] defaults:

使用Vue.use(VueForm, options)或使用mixin mixins: [new VueForm(options)]Vue.use(VueForm, options)设置配置选项mixins: [new VueForm(options)]默认:

{
    validators: {},
    formComponent: 'vueForm',
    formTag: 'form',
    messagesComponent: 'fieldMessages',
    messagesTag: 'div',
    showMessages: '',
    validateComponent: 'validate',
    validateTag: 'div',
    fieldComponent: 'field',
    fieldTag: 'div',
    formClasses: {
      dirty: 'vf-form-dirty',
      pristine: 'vf-form-pristine',
      valid: 'vf-form-valid',
      invalid: 'vf-form-invalid',
      touched: 'vf-form-touched',
      untouched: 'vf-form-untouched',
      submitted: 'vf-form-submitted',
      pending: 'vf-form-pending'
    },
    validateClasses: {
      dirty: 'vf-field-dirty',
      pristine: 'vf-field-pristine',
      valid: 'vf-field-valid',
      invalid: 'vf-field-invalid',
      touched: 'vf-field-touched',
      untouched: 'vf-field-untouched',
      submitted: 'vf-field-submitted',
      pending: 'vf-field-pending'
    },
    inputClasses: {
      dirty: 'vf-dirty',
      pristine: 'vf-pristine',
      valid: 'vf-valid',
      invalid: 'vf-invalid',
      touched: 'vf-touched',
      untouched: 'vf-untouched',
      submitted: 'vf-submitted',
      pending: 'vf-pending'
    },
    Promise: typeof Promise === 'function' ? Promise : null
}

翻译自: https://vuejsexamples.com/comprehensive-form-validation-for-vue-js-2-2/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值