Use async-validator to compile the Form component,

Source: Internet
Author: User

Use async-validator to compile the Form component,

In front-end development, Form verification is a common function. Some ui libraries such as ant. design and Element ui both implement Form components with verification functions. Async-validator is a library that can perform asynchronous data verification. The ant. design and Element ui Form components both use async-validator. This article briefly introduces the basic usage of async-validator and uses this library to implement a simple Form component with the verification function.

1. Basic usage of async-validator

Async-validator checks whether the data is valid and provides prompt information based on the validation rules.

The following describes the basic usage of async-validator.

Import AsyncValidator from 'async-validator' // check the const descriptor = {username: [{required: true, message: 'Enter the username '}, {min: 3, max: 10, message: 'username length is 3-10 '}]} // construct a validatorconst validator = new AsyncValidator (descriptor) const data = {username: 'username'} validator according to the validation rules. validate (model, (errors, fields) => {console. log (errors )})

When the data does not comply with the validation rules, the corresponding error information can be obtained in the validator. validate callback function.

When common validation rules in async-validator cannot meet the requirements, we can compile a custom validation function to verify data. A simple verification function is as follows.

Function validateData (rule, value, callback) {let err if (value = 'xxx') {err = 'noncompliant '} callback (err )} const descriptor = {complex: [{validator: validateData}]} const validator = new AsyncValidator (descriptor)

Async-validator supports asynchronous data verification. Therefore, when writing a custom verification function, the callback function must be called no matter whether the verification is successful or not.

2. Compile the Form component and the FormItem component.

Now I know how to use async-validator. How can I combine this library with the Form component to be compiled.

Implementation

Use a picture to describe the implementation idea.

Form component

The Form component should be a container containing an indefinite number of FormItem or other elements. You can use the built-in slot component of Vue to represent the content in Form.

The Form component also needs to know how many FormItem components need to be verified. In general, the communication between parent and child components is implemented by binding events to child components. However, slots are used here, So events of child components cannot be monitored. You can use $ on to listen to events on the Form component, and trigger custom events of the Form component before FormItem is mounted or destroyed.

Based on this idea, we first compile the Form component.

<Template> <form class = "v-form"> <slot> </form> </template> <script> import AsyncValidator from 'async-validator 'export default {name: 'V-form', componentName: 'vform', // use $ options. componentName: Find the form component data () {return {fields: [], // field: {prop, el}, and save the FormItem information. FormError :{}}, computed: {formRules () {const descriptor ={} this. fields. forEach ({prop}) =>{ if (! Array. isArray (this. rules [prop]) {console. warn (the FormItem validation rule for 'prop $ {prop} does not exist or its value is not an array ') descriptor [prop] = [{required: true}] return} descriptor [prop] = this. rules [prop]}) return descriptor}, formValues () {return this. fields. reduce (data, {prop}) => {data [prop] = this. model [prop] return data },{}) }, methods: {validate (callback) {const validator = new AsyncValidator (this. formRule S) validator. validate (this. formValues, (errors) =>{ let formError ={} if (errors & errors. length) {errors. forEach ({message, field}) =>{ formError [field] = message})} else {formError ={}} this. formError = formError // make the order of error messages the same as that of form components. const errInfo = [] this. fields. forEach ({prop, el}, index) => {if (formError [prop]) {errInfo. push (formError [prop]) }}) callback (errInfo)}) }, props: {Model: Object, rules: Object}, created () {this. $ on ('form. addField ', (field) => {if (field) {this. fields = [... this. fields, field]}) this. $ on ('form. removeField ', (field) => {if (field) {this. fields = this. fields. filter ({prop}) => prop! = Field. prop) }}}</script>

FormItem component

The FormItem component is much simpler. First, you need to find the Form component that contains it. Then, the corresponding error information can be calculated based on formError.

<template> <div class="form-item">  <label :for="prop" class="form-item-label" v-if="label">   {{ label }}  </label>  <div class="form-item-content">   <slot></slot>  </div> </div></template><script>export default { name: 'form-item', computed: {  form () {   let parent = this.$parent   while (parent.$options.componentName !== 'VForm') {    parent = parent.$parent   }   return parent  },  fieldError () {   if (!this.prop) {    return ''   }   const formError = this.form.formError   return formError[this.prop] || ''  } }, props: {  prop: String,  label: String }}</script>

FormItem also needs to trigger some custom events of the Form component in the mounted and beforeDestroy hooks.

<Script> export default {//... methods: {dispatchEvent (eventName, params) {if (typeof this. form! = 'Object '&&! This. form. $ emit) {console. error ('formitem must be in the Form component ') return} this. form. $ emit (eventName, params) }}, mounted () {if (this. prop) {this. dispatchEvent ('form. addField ', {prop: this. prop, el: this. $ el}) }}, beforeDestroy () {if (this. prop) {this. dispatchEvent ('form. removeField ', {prop: this. prop}) }}</script>

Create a new index. js export component.

import VForm from './Form.vue'import FormItem from './FormItem.vue'export { VForm, FormItem}
3. Usage

The Form validation function is in the Form component. You can access the Form component through $ ref and call the validate function to obtain the corresponding verification information.

The usage is as follows:

<Template> <v-form: model = "formData ": rules = "rules" ref = "form"> <form-item label = "mobile phone number" prop = "tel"> <input type = "tel" maxlength = "11" v-model.trim = "formData. tel "/> </form-item> <button @ click =" handleSubmit "> Save </button> </v-form> </template> <script> import {VForm, formItem} from '. /common/Form 'export default {data () {return {formData: {tel: ''}, rules: {tel: [{required: true, message: 'Your mobile phone number is not entered '}, {pattern:/^ 1 [34578] \ d {9 }$/, message: 'Your mobile phone number entered incorrectly '}] }}, methods: {handleSubmit () {this. $ refs. form. validate (errs => {console. log (errs)}) }}, components: {VForm, FormItem }}</script>

Click here for the complete code.

4. Summary

This article briefly introduces the usage of async-validator and implements a Form component with the verification function. The Form implemented here has many shortcomings: (1) it is verified only when the Form is submitted. (2) The FormItem component should also adjust the ui based on the verification results and give corresponding prompts. Therefore, the Form component is more suitable for mobile terminals with less interaction.

You can compile custom Form components based on the Application scenario.

References

Async-validator
Form component of Element ui
Element ui Form source code

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.