element-ui Form forms authentication rule the whole solution
element of form form is very easy to use, comes with validation rules, is easy to use, the official website to the case for some common scenarios no problems, but some validation of complex scenes have their own look at the document and explore their own after a few climb pit
Thereafter, validation rules summary form several forms, for ease of reading, validation rules are resolved, in the end the complete code
1. Normal input validation
<El-form-item label = "event name" prop = "name"> <-! Role validate-event attribute is: Do not trigger revalidation form validation when entering the time of submission, you may also be set to dynamic authentication -> <el-input v-model="registData.name" :validate-event="false"></el-input> </el-form-item> rules: {// Form validation rules name: [ {Required: true, message: 'Please enter the event name'}, // 'blur' the mouse loses focus when it will trigger validation {Min: 3, max: 5, message: 'the length in characters 3-5'} ] }
2. Digital type validation
<El-form-item label = "area of" prop = "area"> <! - when the input type is Number, need to add a modifier to-digital converter, the input box default type is of type String, but I tried it and found that it does not verify, so he wrote a function method validation - > <!-- <el-input v-model.number="registData.area" autocomplete="off"></el-input> --> <-! Keyup is a mouse up event, autocomplete is input comes with native attributes, auto-completion, on to on, off off -> <el-input v-model="registData.area" @keyup.native="InputNumber('area')" autocomplete="off"></el-input> </el-form-item> area: [ // Type Digital 'number', integers: 'integer', Float: 'float' // {type: 'number', message: 'Please enter a numeric type', trigger: 'blur'}, // {type: 'integer', message: 'Please enter a numeric type', trigger: 'change'}, // 'change' value is changed when the form triggers verification {Required: true, message: 'Please input region area', trigger: 'blur'} ], // write their own regular authentication, restricted characters other than the user to enter numbers // amount of input filter InputNumber (property) { this.registData[property] = this.limitInputPointNumber(this.registData[property]) }, // validate numerical only limitInputNumber (val) { if (val) { return String(val).replace(/\D/g, '') } return val }, // limit can only enter numbers (you can enter two decimal places) limitInputPointNumber (val) { if (val === 0 || val === '0' || val === '') { return '' } else { let value = null value = String (val) .replace (/ [^ \ d.] / g, '') // clear the "number" and the outside "." character value = value.replace (/ \. {2,} / g, '.') // keep only the first. Remove excess value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.') value = value.replace (/ ^ (-..) * (\ d +) \ (\ d \ d) * $ /, '$ 1 $ 2. $ 3') // only enter two decimals return Number(value) } },
3.1 Nested authentication (stand-alone authentication)
This situation is a line contains a plurality of input boxes or selected, there are two methods, the first is written el-form nested, independent verification
<El-form-item label = "active time" required> <el-col :span="11"> <el-form-item prop="date1"> <el-date-picker type="date" placeholder="选择日期" v-model="registData.date1" style="width: 100%;"></el-date-picker> </el-form-item> </el-col> <el-col class="line" :span="2">-</el-col> <el-col :span="11"> <el-form-item prop="date2"> <el-time-picker type="fixed-time" placeholder="选择时间" v-model="registData.date2" style="width: 100%;"></el-time-picker> </el-form-item> </el-col> </el-form-item> date1: [ {Type: 'date', required: true, message: 'Please select a date', trigger: 'change'} ], date2: [ {Type: 'date', required: true, message: 'Please select time', trigger: 'change'} ],
3.2 Nested verification (authentication linkage)
After this linkage is validated for linkage provincial scene, the first national election triggered verification city
<-! Region is an object, state and city are its attributes -> <El-form-item label = "active area" prop = "region"> <El-select v-model = "registData.region.country" placeholder = "Please select a country"> <el-option label="国家一" value="USA"></el-option> <el-option label="国家二" value="China"></el-option> </el-select> <El-select v-model = "registData.region.city" placeholder = "Please select a city"> <el-option label="城市一" value="shanghai"></el-option> <el-option label="城市二" value="beijing"></el-option> </el-select> </el-form-item> region: [ { type: 'object', required: true, There are two // process a custom validation, to verify their get the attribute value, more trouble // validator: (rule, value, callback) => { // console.log(55, value) // if (!value.country) { // callback (new Error ( 'Please select a country')) // } else if (!value.city) { // callback (new Error ( 'Please select a city')) // } else { // callback() // } // }, trigger: 'change', // official website provides a nested object verification, just need to need to verify the properties of an object on the fields, the order will be verified fields: { country: {required: true, message: 'Please select a country', trigger: 'blur'}, city: {required: true, message: 'Please select a city', trigger: 'blur'} } } ],
4. The image upload validation (part of the verification method manual trigger)
Sometimes you need to upload pictures to your form, but the picture upload is an asynchronous process, not to trigger validation rules change after property values
<El-form-item label = "moving picture" prop = "fileUrl"> <Electricity-upload :action="action" :on-success="handleSuccess" :data="uploadData" :limit="20" list-type="picture-card" :on-preview="handlePreview" :on-remove="handleRemove"> <i class="el-icon-plus"></i> </el-upload> </el-form-item> fileUrl [ {Required: true, message: 'Please upload pictures', trigger: 'change'} ], // delete pictures handleRemove (file, fileList) { this.registData.fileUrl = '' The method also triggered after verification // file deletion, validateField partial validation is triggered, the parameter value is set prop this.$refs.registerRef.validateField('fileUrl') }, // upload picture handleSuccess (res, file, fileList) { // write here can handle the file uploads successfully, but we must remember to assign fileUrl this.registData.fileUrl = 'fileUrl' Does not trigger a verification form after // file upload form, to be added manually verify this.$refs.registerRef.validateField('fileUrl') },
The full code
<template> <div> <p>shopInfo</p> <div class="company" id="company"> <-! Model is validated data sources -> <el-form :model="registData" :rules="rules" ref="registerRef" label-width="100px" class="demo-ruleForm"> <El-form-item label = "event name" prop = "name"> <! - without triggering form validate-event validation input, then submitting validation may be provided to dynamically verify -> <el-input v-model="registData.name" :validate-event="false"></el-input> </el-form-item> <El-form-item label = "area of" prop = "area"> <! - when the input type is Number, need to add a modifier to-digital converter, the input box default type is of type String, but I tried it and found that it does not verify, so he wrote a function method validation - > <!-- <el-input v-model.number="registData.area" autocomplete="off"></el-input> --> <el-input v-model="registData.area" @keyup.native="InputNumber('area')" autocomplete="off"></el-input> </el-form-item> <El-form-item label = "active area" prop = "region"> <El-select v-model = "registData.region.country" placeholder = "Please select a country"> <el-option label="国家一" value="USA"></el-option> <el-option label="国家二" value="China"></el-option> </el-select> <El-select v-model = "registData.region.city" placeholder = "Please select a city"> <el-option label="城市一" value="shanghai"></el-option> <el-option label="城市二" value="beijing"></el-option> </el-select> </el-form-item> <El-form-item label = "active time" required> <el-col :span="11"> <el-form-item prop="date1"> <el-date-picker type="date" placeholder="选择日期" v-model="registData.date1" style="width: 100%;"></el-date-picker> </el-form-item> </el-col> <el-col class="line" :span="2">-</el-col> <el-col :span="11"> <el-form-item prop="date2"> <el-time-picker type="fixed-time" placeholder="选择时间" v-model="registData.date2" style="width: 100%;"></el-time-picker> </el-form-item> </el-col> </el-form-item> <El-form-item label = "immediate delivery" prop = "delivery"> <el-switch v-model="registData.delivery"></el-switch> </el-form-item> <El-form-item label = "nature of activity" prop = "type"> <el-checkbox-group v-model="registData.type"> <El-checkbox label = "Gourmet / restaurant online activities" name = "type"> </ el-checkbox> <El-checkbox label = "push event" name = "type"> </ el-checkbox> <El-checkbox label = "below the line theme activities" name = "type"> </ el-checkbox> <El-checkbox label = "pure brand exposure" name = "type"> </ el-checkbox> </el-checkbox-group> </el-form-item> <El-form-item label = "special resources" prop = "resource"> <el-radio-group v-model="registData.resource"> <El-radio label = "sponsored online brand"> </ el-radio> <El-radio label = "free space below the line"> </ el-radio> </el-radio-group> </el-form-item> <El-form-item label = "moving picture" prop = "fileUrl"> <Electricity-upload :action="action" :on-success="handleSuccess" :data="uploadData" :limit="20" list-type="picture-card" :on-preview="handlePreview" :on-remove="handleRemove"> <i class="el-icon-plus"></i> </el-upload> </el-form-item> <El-form-item label = "active form" prop = "desc"> <el-input type="textarea" v-model="registData.desc"></el-input> </el-form-item> <el-form-item> <! - passed when the form is submitted by the ref -> <el-button type="primary" @click="submitForm('registerRef')">立即创建</el-button> <el-button @click="resetForm('registerRef')">重置</el-button> </el-form-item> </el-form> </div> </div> </template> <style scoped> .company { padding: 30px; text-align: left; width: 600px; } </style> <script> export default { name: 'shopinfo' data () { return { registData: { name: '', // name area: '', // area region: {}, // Region date1: '', // Date date2: '', // time delivery: false, // immediate delivery type: [], // nature of activities resource: '', // special resources fileUrl: '', // Event Photos desc: '' // form of activity } // need to verify form attributes, the data must be defined in rules: {// Form validation rules name: [ {Required: true, message: 'Please enter the event name'}, // 'blur' the mouse loses focus when it will trigger validation {Min: 3, max: 5, message: 'the length in characters 3-5'} ], area: [ // numeric types // {type: 'number', message: 'Please enter a numeric type', trigger: 'blur'}, // {type: 'integer', message: 'Please enter a numeric type', trigger: 'change'}, // 'change' value is changed when the form triggers verification {Required: true, message: 'Please input region area', trigger: 'blur'} ], region: [ { type: 'object', required: true, // validator: (rule, value, callback) => { // console.log(55, value) // if (!value.country) { // callback (new Error ( 'Please select a country')) // } else if (!value.city) { // callback (new Error ( 'Please select a city')) // } else { // callback() // } // }, trigger: 'change', fields: { country: {required: true, message: 'Please select a country', trigger: 'blur'}, city: {required: true, message: 'Please select a city', trigger: 'blur'} } } ], date1: [ {Type: 'date', required: true, message: 'Please select a date', trigger: 'change'} ], date2: [ {Type: 'date', required: true, message: 'Please select time', trigger: 'change'} ], type: [ {Type: 'array', required: true, message: 'Please select at least one active nature', trigger: 'change'} ], resource: [ {Required: true, message: 'select the active resources', trigger: 'change'} ], fileUrl [ {Required: true, message: 'Please upload pictures', trigger: 'change'} ], desc: [ {Required: true, message: 'Please fill in the form of activity', trigger: 'blur'} ] }, action: `https://jsonplaceholder.typicode.com/posts/`, uploadData: {userId: 1304, pathName: 'company'} } }, created () { }, methods: { // amount of input filter InputNumber (property) { this.registData[property] = this.limitInputPointNumber(this.registData[property]) }, // validate numerical only limitInputNumber (val) { if (val) { return String(val).replace(/\D/g, '') } return val }, // limit can only enter numbers (you can enter two decimal places) limitInputPointNumber (val) { if (val === 0 || val === '0' || val === '') { return '' } else { let value = null value = String (val) .replace (/ [^ \ d.] / g, '') // clear the "number" and the outside "." character value = value.replace (/ \. {2,} / g, '.') // keep only the first. Remove excess value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.') value = value.replace (/ ^ (-..) * (\ d +) \ (\ d \ d) * $ /, '$ 1 $ 2. $ 3') // only enter two decimals return Number(value) } }, // preview picture handlePreview (file) { }, // delete pictures handleRemove (file, fileList) { this.registData.fileUrl = '' The method also triggered after verification // file deletion, validateField partial validation is triggered, the parameter value is set prop this.$refs.registerRef.validateField('fileUrl') }, // upload picture handleSuccess (res, file, fileList) { // write here can handle the file uploads successfully, but we must remember to assign fileUrl this.registData.fileUrl = 'fileUrl' Does not trigger a verification form after // file upload form, to be added manually verify this.$refs.registerRef.validateField('fileUrl') }, submitForm (formName) { console.log(this.registData) this.$refs[formName].validate((valid) => { if (valid) { alert('submit!') } else { console.log('error submit!!') return false } }) }, resetForm (formName) { this.$refs[formName].resetFields() } } }
Method to add two errors displayed
Sometimes we modify the data page, the assignment is empty triggers validation error that occurs when a prop in a form-item control more. This is not the time you want the page to load validation, verification at a particular time, you can use error this property
The initial value of the space-time error will not show an error message if there is value in the page will display an error message
<el-form-item class="region" label="" :error="nameError"> <el-input v-model="registData.name" @change="changeName" :validate-event="false"></el-input> </el-form-item> methods: { data: { return () { nameError: '' } } changeName () { // set when separate error, will not trigger validation el-form, and whether there is value to show only error according to error if (this.registData.name) { this.nameError = '' } else { this.nameError = 'Enter the name' } } }
Another scenario: a custom error style
Error message el-form default is to show the input box at the bottom line, if you need specially style, you can use slot
<el-form-item label="" prop="password"> <el-input v-model="perfectInfo.password" :placeholder="pwdPlaceholder" :maxlength="24" auto-complete="new-password" > </el-input> <template slot="error" slot-scope="slot"> <div class="el-form_tip tt"> <div class="item_tip">{{pwdFormatTips1}}</div> <div class="item_tip">{{pwdFormatTips2}}</div> <div class="item_tip">{{pwdFormatTips3}}</div> <div class="item_tip">{{pwdFormatTips4}}</div> </div> </template> </el-form-item>