Personal summary for element plus form validation

If you are Xiaobai, this set of information can help you become a big bull. If you have rich development experience, this set of information can help you break through the bottleneck
2022web full set of video tutorial front-end architecture H5 vue node applet Video + data + code + interview questions.

preface

Form verification can verify the user's input by setting verification rules, and give corresponding prompts for non-standard input. Element plus (including element UI) provides form verification. However, there are only the most basic usage methods on the official website. For detailed use, please refer to async validator, through which element plus form verification is realized

Element plus form - form validation
async-validator - Git
async-validator - Gitee

1, Basic use of form validation

1. Define validation rules

baseRules: {
  name:[{ required: true, message: 'Please enter the name of the doctor', trigger: 'blur' }],
  title: [{ required: true, message: 'Please select a professional title', trigger: 'change' }],
  gender: [{ required: true, message: 'Please select gender', trigger: 'change' }],
  hospital: [{ required: true, message: 'Please select a hospital', trigger: 'change' }]
},

2. Binding forms and Rules

<el-form :model="formData" :rules="baseRules" ref="baseForm"></el-form>

3. Bind Item and Rule

In the previous step, the rule list baseRules has been bound for the form. Next, you only need to use prop binding validation rules in form item

< El form item label = "name" prop = "name" > < / El form item >

Correspondence:
Form object formdata: {Name: ''}
Form element prop="name"
Rule list baserules: {Name: [{...}]}

4. Examples

<template>
	<el-form :inline="true" :model="doctorDialogForm" size="small" :rules="baseRules" ref="baseForm">
		<el-form-item label="Name of doctor" prop="name">
	      <el-input v-model="doctorDialogForm.name"></el-input>
	    </el-form-item>
		<!-- ... -->
		<template #footer>
		  <span class="dialog-footer">
		    <el-button @click="cancelOperation()">Cancel</el-button>
		    <el-button type="primary" @click="confirmOperation()">determine</el-button>
		  </span>
		</template>
	</el-form>
</template>

<script>
export default {
  name: 'Doctor',
  data() {
    return {
		doctorDialogForm: {       // Modal box - doctor information
		  no: '',                 // Doctor number
		  name: '',               // Name of doctor
		  title: '',              // Doctor title
		  gender: '',             // Gender
		  hospital: '',           // Hospital
		},
		basicRules: {
		  name:[{ required: true, message: 'Please enter the name of the doctor', trigger: 'blur' }],
		  title: [{ required: true, message: 'Please select a professional title', trigger: 'change' }],
		  gender: [{ required: true, message: 'Please select gender', trigger: 'change' }],
		  hospital: [{ required: true, message: 'Please select a hospital', trigger: 'change' }]
		},
	}
  },
  methods: {
  	confirmOperation() {
  		this.$refs.baseForm.validate((valid) => {
  			if(!valid) {
  				this.$message.warning('Please adjust the data before requesting')
  				return false
  			}
  			// operation code
  		})
  	}
  }
}
</script>

2, Basic API (can be skipped first)

async-validator - Git
async-validator - Gitee

1,async-validator

Rules API:

  • Type: indicates the type of verifier to use
    type: string, number, boolean, method, regexp, integer, float, array, object, enum, date, url, hex, email, any
  • Required
    Required: required / not required
  • Messages
    Message: error message
  • Pattern
    pattern: regular expression whose value needs to be verified
  • Range
    Min, Max: refers to the length when the type is array and string. When it is number, it refers to the size
  • Length
    Len: when the type is array and string, it refers to the length. When it is number, it refers to the value
  • Enumerable
    Enum: example: {type: 'enum', enum: ['admin', 'user', 'guest']}
  • Whitespace
  • Deep Rules of the Deep Rules object
    fields: the property name of the object and the subscript of the array
    defaultField: applies to all members in the object and array
  • Transform
    transform: method, preprocessing of values
  • validator
    validator: custom validation method
  • asyncValidator
    asyncValidator: Custom asynchronous validation method

2,element-plus

Trigger: the method to trigger verification. The values can be string 'blur', 'change', or array ['blur', 'change]. The default is all

Note that the rule array is verified one by one in order (when trigger='blur ', changing the value of the input box will not trigger verification)

3, Advanced use

1. Single verification

Validation rules can be set separately in the item of the form (< El form item >)

<el-form-item label="Email:" prop="email"
  :rules="[{ type: 'email', message: 'Email format error', trigger: 'change' }]"
></el-form-item>

2. Custom form validation

You can use the validator to set a custom form validation method

<el-form-item label="Payment method:" prop="payTypes"></el-form-item>


data() {
	return {
		basicRules: {
			payTypes: [{ validator: this.validateOrderPayTypes, trigger: 'change' }]
		}
	}
}
methods: {
    validateOrderPayTypes(rule, value, callback) { // Verify payment method
      if(!value || value.length == 0) { // Customize the verification conditions and return the error prompt text
        callback(new Error('Please add payment method'))
      } else {
        callback()
      }
    },
}

For the maintainability and beauty of the code, try not to write the rules in the template. However, this must be the case in some cases. For example, when additional parameters need to be passed to the validator:

<el-form-item label="Sample type:" prop="sampType"
	:rules="[{ validator: (rule, value, cb) => validateSampType(rule, value, cb, yourParams), trigger: 'change' }]"
></el-form-item>

3. Regular check

element plus async-validator Provides many advanced usages that can be used pattern Specifies the regularity of the check

regex.js:

// Mobile phone number or landline number
export const reg_tel_phone = /(^((+86)|(86))?(1[3-9])d{9}$)|(^(0d{2,3})-?(d{7,8})$)/

doctor.vue:

import { reg_tel_phone } from '@/assets/regex'


baseRules: {
  name: [{ required: true, message: 'Please enter the name of the doctor', trigger: 'blur' }],
  title: [{ required: true, message: 'Please select a professional title', trigger: 'change' }],
  tel: [{ pattern: reg_tel_phone, message: 'Please enter the correct mobile phone number or landline number', trigger: ['blur', 'change'] }]
},

Note: when performing individual verification directly in vue template and using regular verification, RegExp needs to be defined in data(){return {}}

4. Deep (nested) Rules

object and array can be verified by nesting rules. Please refer to for specific parameter configuration async-validator#deep-rules

Use fields to locate the attribute of the object address:

Use defaultField to set validation rules for array elements:

Set the verification rules for the corresponding array elements with subscripts:

Example 1:

baseRules: {
	CCEmails: [{
		type: 'array',
		defaultField: { type: 'email', message: 'Please enter the correct email address' }
	}]
}

Example 2:

import { reg_tel_phone } from '@/assets/regex'

Form Data

regTelPhone: reg_tel_phone,
formBaseInfo: {         // form object 
	noMail: false,      // No mail
	formMails: [{       // Address list
		reciever: '',   // addressee
        recieveTel: '', // Receiving number
        address: {      // Receiving address
          area: [],     // Address zoning list
          detail: ''    // Address Details 
        }
	}]
}

verification

<el-form :model="formBaseInfo" size="mini" :rules="basicRules" ref="ruleBasicForm">
	<!-- 5,Mailing information -->
	<el-form-item
	  label="Mailing information"
	  prop="formMails"
	  :rules="[{
	    type: 'array',
	    required: !formBaseInfo.noMail,
	    defaultField: {
	      type: 'object',
	      fields: {
	        reciever: { required: true, message: 'Please enter the recipient' },
	        recieveTel: [
	        	{ required: true, message: 'Please enter the recipient's phone number' },
	        	{ pattern: regTelPhone, message: 'The phone format is incorrect'}
	        ],
	        address: {
	          type: 'object',
	          required: true,
	          message: 'Please enter address information',
	          fields: {
	            area: {
	              type: 'array',
	              required: true,
	              len: 3,
	              message: 'Please select an address zone',
	              defaultField: { required: true, message: 'Missing area code' }
	            },
	            detail: { required: true, message: 'Please enter the detailed address' }
	          }
	        }
	      }
	    }
	  }]"
	>
		<!-- ... -->
	</el-form-item>
</el-form>

The above example is only an example. The test results are just_ Mailing information_ of If you want more detailed tips, you need to split the nested rules.
As shown in the figure below, the prompt position is always_ Mailing information_ Under the corresponding content, the error cannot be located:

5. Validate attribute values in the array

That is, when the bound form attribute is the attribute value in the array
As shown below, there are multiple products in the form, and there are multiple samples in each product. The products to be verified include product number, sample number, sample user, etc

formData: {
	no: null,
	products: [{          // product
		no: null,
		remark: '',
		key: null,
		samples: [{       // sample
			no: null,
			user: null,
			key: null,
		}]
	}]
}

prop needs to specify the bound properties through string splicing
In the following example, use prop="'formData['+idx+'].no '" instead of prop="product.no"

<el-card v-for="(product,idx) in formData.products" :key="product.key">
	<!-- product -->
	<el-form-item label="Select product:" :prop="'formData['+idx+'].no'"
       :rules="[{ required: true, trigger: 'change', message: 'Please select a product' }]"
	>
     	<el-select v-model="product.no" placeholder="Please select a product">...</el-select>
	</el-form-item>
	<el-form-item label="Product remarks:">...</el-form-item>

	<!-- sample -->
	<el-card v-for="(sample,idx1) in product.samples" :key="sample.key">
		<el-form-item label="Select User:" :prop="'formData['+idx+'].samples['+idx1+'].user'"
          :rules="[{ required: true, trigger: 'change', message: 'Please select a user' }]"
        >
          <el-select v-model="sample.user" placeholder="Please select a user">...</el-select>
        </el-form-item>
	</el-card>
	<el-form-item label="Add sample" label-width="0">...</el-form-item>
</el-card>

When the verified object is the attribute value in the array, the method directly defined in rules cannot be found, so it can only be written in the form of single item verification first

6. Asynchronous custom validator

When there is asynchronous verification in the user-defined validator, the validator cannot implement the verification correctly, so you need to use asyncValidator. The manual verification method before submission is also different

import { reg_tel_phone } from '@/assets/regex'
import { checkTelExistence } from '@/api/common'


data() {
  return {
	baseRules: {
	  tel: [
		{ required: true, message: 'Please enter the phone number' },
		{ pattern: reg_tel_phone, message: 'The phone format is incorrect' },
		{ asyncValidator: this.validateTel, trigger: 'change' }
	  ]
	},
  }
},
methods: {
  // Telephone uniqueness verification
  async validateTel(rule, value, callback) {
    await checkTelExistence(this.salerDialogForm.tel).then(res => {
      callback()
    }).catch(e => {
      callback(new Error(e.message || e.msg || e))
    })
  },
  // Confirm new
  confirmOperation(formName) {
    this.$refs[formName].validate().then(() => {
	  // validation passed or without error message
    }).catch(e => {
      return false
    })
  }
}

summary

This article is only a summary of personal development and learning. Welcome to discuss it in the comment area. If there is any mistake, please correct it!

Keywords: Javascript Front-end html Interview

Added by Hellomonkey on Fri, 18 Feb 2022 22:50:57 +0200