Vue implements form data validation example code

Vue implements form data validation example code
  • Add rules to the el-form form:
  • Define rules in data
  • Bind the defined rules to el-form-item

The code is as follows:

<!--Login form area-->
  <el-form :model="loginForm" label-width="0px" class="login_form" :rules="loginFormRules">
  <!--Username-->
   <el-form-item prop="username">
    <el-input v-model="loginForm.username" prefix-icon="el-icon-user"></el-input>
  </el-form-item>
  <!--Password-->
  <el-form-item prop="password">
    <el-input v-model="loginForm.password" prefix-icon="el-icon-lock" type="password"></el-input>
  </el-form-item>
  <!--Button area-->
  <el-form-item class="btns">
    <el-button type="primary">Login</el-button>
    <el-button type="info">Reset</el-button>
  </el-form-item>
  </el-form>
<script>
 export default{
 data(){
  return {
  //Login form data binding object loginForm:{
   username:'',
   password:''
  },
  //Form validation rules loginFormRules:{
   //Verify whether the username is legal username:[
   { required: true, message: 'Please enter your username', trigger: 'blur' },
   { min: 3, max: 10, message: 'Length is between 3 and 10 characters', trigger: 'blur' }
   ],
   //Verify whether the password is legal password:[
   { required: true, message: 'Please enter your password', trigger: 'blur' },
   { min: 6, max: 15, message: 'Length is between 6 and 15 characters', trigger: 'blur' }
   ]
  }
  }
 }
 }
</script>

PS: Let's take a look at the data validation code of the vue custom directive input form

1. Code

<template>
  <div class="check" >
    <h3>{{msg}}</h3>
    <div class="input">
      <input type="text" v-input v-focus><span>{{msg1}}</span>
    </div>
    <div class="input">
      <input type="text" v-input v-required><span>{{msg2}}</span>
    </div>
    <div class="input">
      <!-- required: true/false means this is a required field -->
      <input type="text" v-input v-checked="{required:true,}"><span>{{msg3}}</span>
    </div>
    <div class="input">
      <!-- <input type="text" v-input v-validate="'required|email|phone|min(5)|max(15)|minlength(6)|maxlength(12)|regex(/^[0-9]*$/)'">
      required Verify if it is a required field email Verify if it is an email address phone Verify if it is a phone number min(5) Verify the minimum value max(3) Verify the maximum value minlength(6) Verify the minimum length maxlength(12) Verify the maximum length regex(/^[0-9]*$/) Perform regular expression verification -->
      <input type="text" v-input
          v-validate="'required|min(5)|max(15)|minlength(6)|maxlength(12)|regex(/^[0-9]*$/)'" placeholder="Multiple selection validation">
    </div>
    <div class="input">
      <!--
      Verification must be a number: /^[0-9]*$/
      Verify a string consisting of 26 English letters: /^[A-Za-z]+$/
      Verify mobile phone number: /^[1][3,4,5,7,8][0-9]{9}$/;
      Verify email address: /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
      -->
      <input type="text" v-input v-validate="'required|phone'" placeholder="Verify phone number">
    </div>
    <div class="input">
      <input type="text" v-input v-validate="'required|email'" placeholder="Verify email">
    </div>
  </div>
</template>

<script>
  export default {
    name: 'check',
    data() {
      return {
        msg: 'Command',
        tipsBorderColor: 'red',
        msg1: 'The simplest instruction',
        msg2: 'Verification cannot be empty instructions',
        msg3: 'Perform regular verification',
        tipsMsg: '',
      }
    },

    directives: {
      // Modify the input box command input: {
        // When the bound element is inserted into the DOM inserted: function (el) {
          el.style.width = "300px";
          el.style.height = "35px";
          el.style.lineHeight = "35px";
          el.style.background = "#ddd";
          el.style.fontSize = "16px";
          el.style.border = "1px solid #eee";
          el.style.textIndent = "5px";
          el.style.textIndent = "8px";
          el.style.borderRadius = "5px";
        }
      },
      // The default selected command of the input box focus: {
        inserted: function (el) {
          el.focus();
        }
      },
      // Instructions that cannot be empty required: {
        inserted: function (el) {
          el.addEventListener('blur', function () {
            if (el.value == '' || el.value == null) {
              el.style.border = "1px solid red";
              console.log('I can't be empty');
            }

          })
        }
      },
      // Verify the command checked: {
        inserted: function (el) {
          return el
        }
      },
      // Validate: {
        inserted: function (el, validateStr) {
          // Split validation rules into validation arrays let validateRuleArr = validateStr.value.split("|");
          // Listen for loss of focus el.addEventListener('blur', function () {
            // Lose focus to verify checkedfun();
          });

          //Loop verification function checkedfun() {
            for (var i = 0; i < validateRuleArr.length; ++i) {
              let requiredRegex = /^required$/; // Check if required is set
              let emailRegex = /^email$/; // Determine if email is set
              let phoneRegex = /^phone$/; // Check if phone is set
              let minRegex = /min\(/; //Judge whether the min minimum value is set let maxRegex = /max\(/; //Judge whether the max maximum value is set let minlengthRegex = /minlength\(/; //Judge whether the minlength maximum length is set let maxlengthRegex = /maxlength\(/; //Judge whether the maxlength maximum length is set let regexRegex = /regex\(/;
              // Check if required is set
              if (requiredRegex.test(validateRuleArr[i])) {
                if (!required()) {
                  break;
                } else {
                  removeTips();
                }

              }

              // Determine if email is set
              if (emailRegex.test(validateRuleArr[i])) {
                if (!email()) {
                  break;
                } else {
                  removeTips();
                }

              }

              // Determine if phone is set
              if (phoneRegex.test(validateRuleArr[i])) {
                if (!phone()) {
                  break;
                } else {
                  removeTips();
                }

              }

              // Determine whether the minimum value is set if (minRegex.test(validateRuleArr[i])) {
                if (!eval(validateRuleArr[i])) {
                  break;
                } else {
                  removeTips();
                }

              }

              // Determine whether the maximum value is set if (maxRegex.test(validateRuleArr[i])) {
                if (!eval(validateRuleArr[i])) {
                  break;
                } else {
                  removeTips();
                }

              }

              // Check if the minimum length is set if (minlengthRegex.test(validateRuleArr[i])) {
                if (!eval(validateRuleArr[i])) {
                  break;
                } else {
                  removeTips();
                }

              }

              // Check if the maximum length is set if (maxlengthRegex.test(validateRuleArr[i])) {
                if (!eval(validateRuleArr[i])) {
                  break;
                } else {
                  removeTips();
                }

              }

              // Judge the test regular expression if (regexRegex.test(validateRuleArr[i])) {
                if (!eval(validateRuleArr[i])) {
                  break;
                } else {
                  removeTips();
                }

              }

            }

          }

          // Verify whether it is a required field function required() {
            if (el.value == '' || el.value == null) {
              // console.log("cannot be empty");
              tipMsg("cannot be empty");
              return false;
            }

            return true;
          }

          // Verify whether it is an email function email() {
            let emailRule = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
            if (!emailRule.test(el.value)) {
              tipMsg("Please enter a valid email address");
              return false;
            }

            return true;
          }

          // Verify whether it is a mobile phone number function phone() {
            let phoneRule = /^[1][3,4,5,7,8][0-9]{9}$/;
            if (!phoneRule.test(el.value)) {
              tipMsg("Please enter a valid mobile phone number");
              return false;
            }

            return true;
          }

          // Minimum value verification function min(num) {
            if (el.value < num) {
              tipMsg("The minimum value cannot be less than " + num);
              //console.log('The minimum value cannot be less than '+num);
              return false;
            }

            return true;
          }

          // Maximum value verification function max(num) {
            if (el.value > num) {
              tipMsg("The maximum value cannot be greater than " + num);
              //console.log('The maximum value cannot be greater than '+num);
              return false;
            }

            return true;
          }

          // Minimum length verification function minlength(length) {
            if (el.value.length < length) {
              //console.log('The minimum length cannot be less than '+length);
              tipMsg("Minimum length cannot be less than" + length);
              return false;
            }

            return true;
          }

          // Maximum length for verification function maxlength(length) {
            if (el.value.length > length) {
              //console.log('The maximum length cannot be greater than '+length);
              tipMsg("The maximum length cannot be greater than" + length);
              return false;
            }
            return true;
          }

          // Validate the regular expression function regex(rules) {
            if (!rules.test(el.value)) {
              tipMsg("Please enter the correct format");
              return false;
            }
            return true;
          }

          // Add prompt information function tipMsg(msg) {
            removeTips();
            let tipsDiv = document.createElement('div');
            let curDate = Date.parse(new Date());
            tipsDiv.innerText = msg;
            tipsDiv.className = "tipsDiv";
            tipsDiv.id = curDate;
            tipsDiv.style.position = "absolute";
            tipsDiv.style.top = el.offsetTop + 45 + 'px';
            tipsDiv.style.left = el.offsetLeft + 'px';
            document.body.appendChild(tipsDiv);
            //setTimeout(function(){
            // document.getElementById(curDate).remove();
            //},2000);
          }

          // Remove the tips function removeTips() {
            if (document.getElementsByClassName('tipsDiv')[0]) {
              document.getElementsByClassName('tipsDiv')[0].remove();
            }

          }
        },
      }
    }
  }
</script>

<style>

  .input {
    padding-bottom: 20px;
    float: left;
    clear: both;
    margin-left: 500px;
    display: block;

  }

  .check input {
    width: 300px;
    height: 35px;
    outline: none;
    background: #ddd;
  }

  .check span {
    padding-left: 20px;
  }

  .tipsDiv {
    height: 27px;
    line-height: 25px;
    border: 1px solid #333;
    background: #333;
    padding: 0px 5px;
    border-radius: 4px;
    color: #fff;
    font-size: 16px;
  }

  .tipsDiv:before {
    content: '';
    display: block;
    border-width: 0 5px 8px;
    border-style: solid;
    border-color: transparent transparent #000;
    position: absolute;
    top: -9px;
    left: 6px;
  }
</style>

Summarize

This is the end of this article about the example code of implementing form data validation in Vue. For more relevant Vue form data validation content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of Vue form event data binding
  • Detailed analysis of vue form data binding
  • Detailed explanation of Vue form control data binding method
  • Vue.js basic instruction example explanation (various data binding, form rendering summary)
  • How to get form data in Vue

<<:  JavaScript to achieve product query function

>>:  Example of how to exit the loop in Array.forEach in js

Recommend

Use of MySQL stress testing tool Mysqlslap

1. MySQL's own stress testing tool Mysqlslap ...

Sharing of experience on repairing MySQL innodb exceptions

A set of MySQL libraries for testing. The previou...

Detailed explanation of the use of the clip-path property in CSS

Use of clip-path polygon The value is composed of...

Nginx configures the same domain name to support both http and https access

Nginx is configured with the same domain name, wh...

How to use Docker to build a development environment (Windows and Mac)

Table of contents 1. Benefits of using Docker 2. ...

Introduction to setting up Tomcat to start automatically on Linux system

1. Enter the /etc/init.d directory: cd /etc/init....

Vue component organization structure and component registration details

Table of contents 1. Component Organization 2. Co...

How to Install Xrdp Server (Remote Desktop) on Ubuntu 20.04

Xrdp is an open source implementation of Microsof...

A brief discussion on HTML ordered lists, unordered lists and definition lists

Ordered List XML/HTML CodeCopy content to clipboa...

MySql 8.0.16-win64 Installation Tutorial

1. Unzip the downloaded file as shown below . 2. ...

MySQL 5.7.17 installation graphic tutorial (windows)

I recently started learning database, and I feel ...

When backing up files in Centos7, add the backup date to the backup file

Linux uses files as the basis to manage the devic...