This is the second day of my participation in Gwen Challenge

The form verification link that often appears in the project is generally a form, which can be verified in one wave when submitting. It is inevitable to encounter complicated business. When a form cannot meet the requirements, it is necessary to set up multiple forms, and the verification method also needs to be adjusted slightly

Common forms validation methods

Form validation

validate()

// Set rules <template> <el-form ref="createForm" :model="createTask" :rules="rules" label-width="120px" > // Here is prop, <el-input V-model ="createTask. Task_name "placeholder=" placeholder" ></el-input> </el-form-item> ... </el-form> </template> <script> // other items omitted data() {return {createTask: {task_name: ",... }, rules: {task_name: [{required: true, message: 'Please enter the name ', trigger: 'blur'}, {min: 5, Max: 22, message: 'Length between 5 and 22 characters ', trigger: 'blur'} // Other validation Settings...] . } } }, methods: $refs.createForm.validate((valid) => {if (valid) {// submit Fn} else  { // error } }) }, Async xxxFn() {try {// valid await this.$refs.createForm.validate() // submit API await submit({params}) // success } catch (error) { // error } } } </script>Copy the code

Validate a field

validateField()

Change the method based on the example above

this.$refs.createForm.validateField('task_name')
Copy the code

Validates multiple fields, passing in arrays

this.$refs.createForm.validateField(['task_name','xxx',...] )Copy the code

Clear form validation

clearValidate()

this.$refs.createForm.clearValidate()
Copy the code

To distinguish it from resetFields(), clearValidate() removes the validation effect, pretending it has not been validated, and resetFields() resets the entire form, resetting all field values to their original values, removing the validation effect, and returning the form to its original state

Clear a field validation

The clear method remains unchanged, and the parameter is directly passed

this.$refs.createForm.clearValidate('task_name')
Copy the code

Similarly, clear multiple field field validations and pass in an array

this.$refs.createForm.clearValidate(['task_name','xxx',...] )Copy the code

Custom method validation

Custom conditions

Data () {// let checkName = (rule, value, Callback) => {if (value === '') {callback(new Error(' cannot be null '))} else if (value! Task_name == 'default') {callback(new Error(' default'))} else {callback()}} return {rules: {// [{required: true, validator: checkName, trigger: 'blur'}}}Copy the code

Invoke backend API validation

Data () {let checkName = (rule, value, callback) => {if (value === ") {callback(new Error(' cannot be null '))} else if (value! == 'default') {callback(new Error(' default'))} else {let result = this.checkTaskNamefn (value) result. then((data) => {if (data) {callback()} else {callback(new Error(' Validation does not satisfy.. '))}}). The catch ((res) = > {callback (new Error (' Error does not meet)))})}} / / the above rules} the methods: { checkTaskNameFn(value) { return new Promise(async (resolve, reject) => { try { await checkAPI({params}) resolve(true) } catch (error) { reject(false) } }) } }Copy the code

The regular verification

Set the rules

Rules: {task_name: [{required: true, message: 'Please enter the name ', trigger: 'blur'}, {pattern: / (?! ^ [0-9] + $) (?! ^ [a-z] + $) (?! ^ [^ A - z0-9] + $). ^ 6, 20} {$/, the message: 'format is not correct'}}]Copy the code

Custom combination validation

When you encounter tedious requirements such as regex and other conditions, the rules setting cannot fully meet the requirements. You can also use custom conditions

Here’s a rare example of a messy regex validation requirement I’ve come across to try it out:

The value contains 8 to 16 characters including digits, uppercase and lowercase letters, and special characters. The value cannot exceed three special characters and must contain the following characters: ~ @ # $% * _ – + = :,.? [] {}”

data() { let checkName = (rule, value, callback) => { let sRegex = '^(? =.*\d)(? =.*[A-Z])(? =.*[a-z])(? =. * [~ + = : @ # $% *,?. _ \ - {} \ [\]], [\ ~ da zA - Z + = : @ # $% *,?. _ \ {} \ [\]] - 16th {8} $' let num = value. The replace (/ [^ ~ + = : @ # $% *,?. _ \ {} \ [\]] - a/g, '').length let reg = new RegExp(sRegex) if (! Value) {callback(new Error(' cannot be null '))} else if (! Reg.test (value) {callback(new Error(' not enough '))} else if (num > 3) {callback(new Error(' not enough '))} else {// Other conditions // or combinatorial API validation... callback() } } }Copy the code

Multi-form validation

Sample two forms

    <el-form
        ref="formA"
        :model="modelA"
        :rules="rulesA"
    ></el-form>

    <el-form
        ref="formB"
        :model="modelB"
        :rules="rulesB"
    ></el-form>
Copy the code

The verification conditions are optional, and the verification methods are as follows:

// Define the following methods: $refs.forma.validate ((valid) => {if (valid) {formA = valid... }else{ ... $refs.formb.validate ();}} let formB = this.$refs.formb.validate (); If (formA &&formb) {return true} else {return false} let formB = await this.$refs.formb.validate () }, Async handleNext() {try {// valid let isValid = await this.validateAllForm () // true && submit} catch (error) { // error } } }Copy the code

The above are some of the verification poses that I tested and used in the project. CV them together according to the specific needs of each project