Vue uses rules to implement form field validation

Vue uses rules to implement form field validation

There are many ways to write and validate form fields in Vue. This blog introduces three more commonly used validation methods.

1. Write in data for verification

Form Contents

<!-- Form -->
<el-form ref="rulesForm" :rules="formRules" :model="rulesForm" label-width="200px">
    <el-form-item label="User Name:" prop="userName">
       <el-input v-model="rulesForm.userName" style="width:300px" maxlength="50"/>
    </el-form-item>
</el-form>
  • <el-form>: represents this is a form
  • <el-form> -> ref: the name of the form when it is referenced, identification
  • <el-form> -> rules: form validation rules
  • <el-form> -> model: form data object
  • <el-form> -> label-width: The width of the form field label. The form-item, which is a direct child element of Form, will inherit this value.
  • <el-form> -> <el-form-item>: each sub-element in the form
  • <el-form-item> -> label: label text
  • <el-form-item> -> prop: form field model field. This attribute is required when using the validate and resetFields methods.
  • <el-input>: input box
  • <el-input> -> v-model: bound form data object properties
  • <el-input> -> style: inline style
  • <el-input> -> maxlength: Maximum character length limit

data

data() {
    return {
        //Omit other data definitions...
        
        // Form validation formRules: {
            userName: [
                {required: true,message: "Please enter your username",trigger: "blur"}
            ]
        }
    }
}
  • formRules: Same as the :rules attribute value of the <el-form> form in 'Form Content' above
  • userName: Same as the prop attribute value of the <el-form-item> form subelement in 'Form Content' above
  • Verification content is: required, verification when losing focus, if empty, prompt message is 'Please enter user name'

2. Write inline

Form Contents

<!-- Form -->
<el-form ref="rulesForm" :rules="formRules" :model="rulesForm" label-width="200px">
    <el-form-item label="Bank Name:" prop="accountName" :rules="[{required:true,message:'Please enter the bank name',trigger:'blur'}]">
        <el-input v-model="rulesForm.accountName" style="width:300px" maxlength="50"/>
    </el-form-item>
</el-form>
  • <el-form-item> -> rules: The effect is the same as the first method, but the writing method is different, so I will not go into details here.

data data has no content

3. Importing externally defined rules

Form Contents

<!-- Form -->
<el-form ref="rulesForm" :rules="formRules" :model="rulesForm" label-width="200px">
    <el-form-item label="Bank card number:" prop="accountNumber">
       <el-input v-model="rulesForm.accountNumber" style="width:300px" maxlength="19"/>
    </el-form-item>
</el-form>

The form content is consistent with the first method, so I won’t go into details here.

Script content

<script>
// Introducing external validation rules import { validateAccountNumber } from "@/utils/validate";
 
// Determine whether the bank card account is correct const validatorAccountNumber = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("Please enter your account information"));
  } else {
    if (validateAccountNumber(value)) {
      callback();
    } else {
      return callback(new Error('Incorrect account format'))
    }
  }
};
 
export default {
    data() {
        return {
            //Omit other data definitions...
        
            // Form validation formRules: {
                accountNumber: [
                    {required: true,validator: validatorAccountNumber,trigger: "blur"}
                ]
            }
        }
    }
}
</script>
  • import: first introduce external validation rules
  • const: defines a rule constant. The constant name is variable. '= (rule, value, callback) => {}' is a fixed format. The value parameter is the field value to be verified.
  • formRules -> accountNumber: Use validator in form validation to specify the name of the custom validation rule constant

validate.js

/* Bank Account */
export function validateAccountNumber(str) {
  const reg = /^([1-9]{1})(\d{14}|\d{18})$/
  return reg.test(str)
}
  • Validation Rules

The above are all verifications when losing focus. Let's analyze how to verify when the form is submitted.

1. Submit button of the form

<!-- Form -->
<el-form ref="rulesForm" :rules="formRules" :model="rulesForm" label-width="200px">
    <el-form-item>
        <el-button type="primary" @click="onSubmit('rulesForm')">Save</el-button>
        <el-button @click="cancel">Cancel</el-button>
    </el-form-item>
</el-form>
  • <el-button>: button
  • <el-button> -> type: button type
  • <el-button> -> @click: The event triggered when the button is clicked. Note that the input parameter of the method is 'rulesForm', which must be consistent with the rel attribute value of the <el-form> form.

2. Methods

methods: {
    // Save onSubmit(formName) {
        this.$refs[formName].validate(valid => {
            if (valid) {
                console.log("success submit!!");
            }else{
                console.log("error submit!!");
            }
        });
    },
    // Cancel cancel() {
        
    }
}

this.$refs[formName].validate: formName is the passed 'rulesForm', which is consistent with the rel attribute value of the <el-form> form, so that the form that needs to be validated is specified

The complete sample code is as follows

1. rules.vue

<template>
  <div class="app-container">
    <el-tabs v-model="activeName">
      <el-tab-pane label="Form" name="rulesPane" @tab-click="handleClick">
        <!-- Form -->
        <el-form ref="rulesForm" :rules="formRules" :model="rulesForm" label-width="200px">
          <el-form-item label="User Name:" prop="userName">
            <el-input v-model="rulesForm.userName" style="width:300px" maxlength="50"/>
          </el-form-item>
          <el-form-item label="Bank Name:" prop="accountName" :rules="[{required:true,message:'Please enter the bank name',trigger:'blur'}]">
            <el-input v-model="rulesForm.accountName" style="width:300px" maxlength="50"/>
          </el-form-item>
          <el-form-item label="Bank card number:" prop="accountNumber">
            <el-input v-model="rulesForm.accountNumber" style="width:300px" maxlength="50"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit('rulesForm')">Save</el-button>
            <el-button @click="cancel">Cancel</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
 
<script>
import { validateAccountNumber } from "@/utils/validate";
 
// Determine whether the bank card account is correct const validatorAccountNumber = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("Please enter your account information"));
  } else {
    if (validateAccountNumber(value)) {
      callback();
    } else {
      return callback(new Error('Incorrect account format'))
    }
  }
};
 
export default {
  name: "rules",
  data() {
    return {
      activeName: "rulesPane",
      defaultProps: {
        children: "children",
        label: "label"
      },
      rulesForm: {
      },
      // Form validation formRules: {
        userName: [
          {
            required: true,
            message: "Please enter your user name",
            trigger: "blur"
          }
        ],
        accountNumber: [
          {
            required: true,
            validator: validatorAccountNumber,
            trigger: "blur"
          }
        ],
      }
    };
  },
  created() {},
  mounted() {},
  methods: {
    handleClick(tab) {
      
    },
    // Cancel cancel() {
      
    },
    // Save onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log("success submit!!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>
 
<style lang="scss">
</style>

2. validate.js

/* Bank Account */
export function validateAccountNumber(str) {
  const reg = /^([1-9]{1})(\d{14}|\d{18})$/
  return reg.test(str)
}

Rendering

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • The production process of Vue form validation plug-in
  • Detailed explanation of how to use Vue Validator, a Vue form validation plugin
  • Vue uses rules to verify form fields
  • Vue custom form content check rules example
  • Detailed explanation of how Vue uses rules to validate form fields
  • Do you really know how to do Vue form validation? vue form validation (form) validate
  • Problems encountered in Form validation of Vue ElementUI
  • Vue+elementUI implements form and image upload and verification function example
  • Form item validation method in v-for loop when using Element component in Vue
  • Implementation of Vue elementui form validation

<<:  How to use IDEA to configure tomcat and create JSP files

>>:  Detailed explanation of how to create multiple instances of MySQL 5.6 in centos7 environment

Recommend

How to deploy hbase using docker

Standalone hbase, let’s talk about it first. Inst...

Detailed explanation of JS browser event model

Table of contents What is an event A Simple Examp...

mysql trigger creation and usage examples

Table of contents What is a trigger Create a trig...

JavaScript to achieve fireworks effects (object-oriented)

This article shares the specific code for JavaScr...

Steps to set up HTTPS website based on Nginx

Table of contents Preface: Encryption algorithm: ...

About ROS2 installation and docker environment usage

Table of contents Why use Docker? Docker installa...

A brief discussion on Vue3 father-son value transfer

Table of contents From father to son: 1. In the s...

Methods and steps to access Baidu Maps API with JavaScript

Table of contents 1. Baidu Map API Access 2. Usin...

Detailed introduction to CSS priority knowledge

Before talking about CSS priority, we need to und...

MySql 5.7.20 installation and configuration of data and my.ini files

1. First download from the official website of My...

How to declare a cursor in mysql

How to declare a cursor in mysql: 1. Declare vari...

Mac installation mysqlclient process analysis

Try installing via pip in a virtual environment: ...

Nginx proxy axios request and precautions

Preface I recently wrote a small demo. Because I ...