Home > Web Front-end > Front-end Q&A > How to write inspection rules in vue method

How to write inspection rules in vue method

王林
Release: 2023-05-24 09:25:37
Original
647 people have browsed it

Vue is a popular JavaScript framework often used to build SPA (Single Page Application) applications. In Vue applications, validating user input is a very important part. In Vue, you can check the validity of user input by defining some rules and methods to ensure that it meets the needs of the application and ensures data security.

Vue provides some built-in validation rules, such as: required, email, numeric, etc. You can perform data binding with input and form elements, bind validation rules directly to the corresponding elements, and bind data to Vue instance data through the v-model directive. In addition, you can also customize rules and methods for data validation.

1. Built-in validation rules

1. required

The function of the required rule is to determine whether the input box is empty. If it is empty, the verification fails.

Used in the template:

<input type="text" v-model="name" required>
Copy after login

Used in the Vue instance:

data() {
  return {
    name: ''
  }
}
Copy after login

2. email

The function of the email rule is to determine whether the input is legal. Email format.

Used in templates:

<input type="email" v-model="email" required>
Copy after login

Used in Vue instances:

data() {
  return {
    email: ''
  }
}
Copy after login

3. numeric

The function of numeric rules is to determine whether the input is pure Number format.

Used in templates:

<input type="number" v-model="age" required>
Copy after login

Used in Vue instances:

data() {
  return {
    age: ''
  }
}
Copy after login

2. Custom rules

In addition to using the built-in rules provided by Vue In addition, you can also customize rules to validate user input. Custom rules can be customized according to the needs of the application. For example, the input data must be within a specific range, must conform to specific regular expressions, must meet certain data formats, etc. Custom rules can be implemented using the Vue.directive method, and a verification function can be passed in when binding.

The template usage of custom rules is similar to the built-in rules. First, define a verification instruction in the template, and then pass the custom rule instruction to the v-bind instruction of the input element, so that it can be used in the input box. Custom rules are triggered when out of focus.

Implementation of custom rules:

Vue.directive('my-rule', {
  bind: function(el, binding, vnode) {
    el.addEventListener('blur', function() {
      const value = el.value
      const rule = binding.value.rule // 获取规则
      const errorMessage = binding.value.message // 获取错误提示信息
      const isValid = rule(value) // 验证数据
      if (!isValid) { // 显示错误提示
        const errorElement = document.createElement('div')
        errorElement.innerHTML = errorMessage
        errorElement.style.color = 'red'
        insertAfter(errorElement, el)
      } else { // 清除错误提示
        const errorElement = nextSibling(el)
        if (errorElement.nodeType === 1 && errorElement.className === 'error-msg') {
          el.parentNode.removeChild(errorElement)
        }
      }
    })
  }
})

// 实例
new Vue({
  el: '#app',
  data() {
    return {
      name: '',
      age: ''
    }
  },
  methods: {
    // 自定义规则
    myRule(value) {
      return value.length === 4 && /^d+$/.test(value)
    }
  }
})
Copy after login

Use custom rules in the template and pass my-rule to the custom rule directive in the v-bind directive:

<input type="text" v-model="name" v-my-rule="{rule: myRule, message: '年龄必须是4位纯数字'}">
Copy after login

3. Custom method

Custom method can also be used for data verification, mainly by writing a function to determine whether the input conforms to the rules, and then binding it through the v-on instruction in the template For the corresponding event, call the custom method in the code that binds the event.

Writing custom methods in Vue:

methods: {
  myMethod(value) {
    return value.length === 11 && /^1d{10}$/.test(value)
  }
}
Copy after login

Calling custom methods in templates:

<input type="text" v-model="phone" v-on:blur="checkPhone">
Copy after login
methods: {
  checkPhone() {
    const phone = this.phone
    const isValid = this.myMethod(phone)
    if (!isValid) {
      alert('请输入正确的手机号码')
    }
  }
}
Copy after login

Summary:

Data validation in Vue is A basic function of Vue program development, through the use of built-in rules, custom rules, custom methods and other technical means, the data verification function can be effectively realized. During the development process, the reasonable use of these technologies to verify user input can not only improve the security and stability of the program, but also improve the user experience.

The above is the detailed content of How to write inspection rules in vue method. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template