Vue implements form validation function

Vue implements form validation function

This article mainly describes how to implement form validation based on NUXT's validate method.

After encapsulating the verification method, you only need to use one line of code like: rules="filter_rules({required:true,type:'mobile'})" to implement verification on the page.

First, let's look at the implementation effect

1. Create a new validate.js file:

This document contains some required validation rules. Let's look at the code directly below:

/**
* Created by jiachenpan on 16/11/18.
**/
 
 
 
export function isvalidUsername (str) {
  const valid_map = ['admin', 'editor']
 return valid_map.indexOf(str.trim()) >= 0
 
}
 
// Non-negative number export function noFuNumber (str) {
  const reg = /^\d+(\.{0,1}\d+){0,0}$/ 
 return reg.test(str)
 
}
 
// Mobile phone number export function isvalidMobile (str) { 
  const reg = /^1(3|4|5|7|8)\d{9}$/ 
 return reg.test(str)
 
}
 
// Chinese, English, numbers export function regexn (str) {
  const reg = /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/ 
 return reg.test(str)
 
}
 
/* Legal URI */ 
export function validateURL (textval) { 
const urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/ 
return urlregex.test(textval)
 
}
  
 
/* lowercase letters*/ 
export function validateLowerCase (str) {
  const reg = /^[az]+$/
 return reg.test(str)
 
}
 
  
/* uppercase letter*/ 
export function validateUpperCase (str) { 
   const reg = /^[AZ]+$/ 
 return reg.test(str)
 
}
 
 
/* Uppercase and lowercase letters*/ 
export function validateAlphabets (str) {
  const reg = /^[A-Za-z]+$/
 return reg.test(str)
 
}
 
 
/**
* validate email
* @param email
* @returns {boolean}
*/

2. Create a new filter_rules.js file:

This document contains validation callback functions and validation fields.

Attached code:

import { isvalidMobile, regexn, noFuNumber } from '@/utils/validate' 
export default {
install (Vue) {
 
/**
* Note: When defining type rules, you do not need to do non-empty validation. * You only need to pass in required:true. * /
 
/* Check if the number is non-negative */
 
const isnoFuNumber = (rule, value, callback) => { 
 if (value != null && value !== '') { 
 if (!noFuNumber(value)) { 
  callback(new Error('Please enter a non-negative number!')) 
 } else {
 
callback()
 
}
 
} else { 
callback()
 
}
 
}
 
/* Verify phone number*/
const isvalidateMobile = (rule, value, callback) => { 
if (value != null && value !== '') {
if (!isvalidMobile(value)) {
callback(new Error('Please enter a correct mobile phone number!'))
 
  } else {
callback()
}
 
   } else { 
callback()
 
}
 
}
 
/* Contains illegal characters (only Chinese, English, and numbers can be entered) */ 
const isvalidateRegexn = (rule, value, callback) => { 
if (value != null && value !== '') { 
if (!regexn(value)) { 
callback(new Error('Contains illegal characters (only Chinese, English, and numbers can be entered)!'))
 
} else {
 
callback() 
}
 
} else { 
callback()
 
}
 
}
 
/* Please enter a positive integer*/
 
// const isvalidateInteger = (rule, value, callback) => { 
// if (value != null && value != "") { 
// if (!integer(value)) { 
// callback(new Error('Please enter a positive integer!')) 
// } else { 
// callback() 
// } 
// } 
// else {
 
// callback(); 
// } 
// }
 
 
 
/**
* Parameter item
* required true Required field* maxLength Maximum length of the string* min and max must be given at the same time min < max type=number
* type mobile phone number
* Email
* URL
* Various custom type definitions are continuously added in src/utils/validate.......
* */
 
 
Vue.prototype.filter_rules = function (item) {
let rules = [] 
if (item.required) { 
rules.push({ required: true, message: 'This input is required!', trigger: 'blur' })
 
}
 
if (item.maxLength) {
rules.push({ min: 1, max: item.maxLength, message: 'Enter at most' + item.maxLength + 'characters!', trigger: 'blur' })
 
}
 
if (item.min && item.max) {
rules.push({ min: item.min, max: item.max, message: 'The character length is between ' + item.min + ' and ' + item.max + '!', trigger: 'blur' })
 
}
 
if (item.type) { 
let type = item.type
switch (type) {
 
// case 'email': 
// rules.push({ type: 'email', message: 'Please enter a valid email address', trigger: 'blur,change' }) 
// break isnoFuNumber
 
case 'activeOrder': 
rules.push({ validator: isnoFuNumber, trigger: 'blur' }) 
break
 
case 'mobile': 
rules.push({ validator: isvalidateMobile, trigger: 'blur' }) 
break

case 'name': 
rules.push({ validator: isvalidateRegexn, message: 'Please enter a valid user name', trigger: 'blur' })
break
 
case 'password': 
rules.push({ validator: isvalidateRegexn, message: 'Please enter your password', trigger: 'blur' }) 
break
 
case 'org_name': 
rules.push({ validator: isvalidateRegexn, message: 'Organization name cannot contain special characters', trigger: 'blur' }) 
break
 
 
default:
 
rules.push({})
 
break
 
}
 
}
 
 
return rules
 
}
 
}
 
}

3. Introduce in the page:

import Validate from '@/utils/filter_rules'

4. Use verification in the page:

The validation rules need to be written in the el-form-item tag.

It should be noted that:

The names of these three places should be written consistently.

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:
  • Do you really know how to do Vue form validation? vue form validation (form) validate
  • Detailed explanation of how to use Vue Validator, a Vue form validation plugin
  • 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
  • Vue quickly implements universal form validation function
  • Implementation of Vue elementui form validation
  • Vue uses element-ui to implement form validation
  • Vue implements small form validation function
  • Vue implements form to remove a field validation separately

<<:  Ubuntu 20.04 Best Configuration Guide (Newbie Essential)

>>:  Which is faster among MySQL full-text index, joint index, like query, and json query?

Recommend

JavaScript object built-in objects, value types and reference types explained

Table of contents Object Object Definition Iterat...

Build a Docker private warehouse (self-signed method)

In order to centrally manage the images we create...

Detailed explanation of Kubernetes pod orchestration and lifecycle

Table of contents K8S Master Basic Architecture P...

25 CSS frameworks, tools, software and templates shared

Sprite Cow download CSS Lint download Prefixr dow...

hr horizontal line style example code

Copy code The code is as follows: <hr style=&q...

Detailed code examples of seven methods for vertical centering with CSS

When we edit a layout, we usually use horizontal ...

How to use VUE to call Ali Iconfont library online

Preface Many years ago, I was a newbie on the ser...

How to download excel stream files and set download file name in vue

Table of contents Overview 1. Download via URL 2....

How to implement n-grid layout in CSS

Common application scenarios The interfaces of cu...

Vue monitoring properties and calculated properties

Table of contents 1. watch monitoring properties ...

Implementation of installing and uninstalling CUDA and CUDNN in Ubuntu

Table of contents Preface Install the graphics dr...

MySQL Series 12 Backup and Recovery

Table of contents Tutorial Series 1. Backup strat...

MySQL column to row conversion, method of merging fields (must read)

Data Sheet: Column to row: using max(case when th...