Table of Contents
Parts of async-validator
Default rules for Rules
Default Type
Deep Rules使用demo
自定义验证validator
Home Web Front-end JS Tutorial Basic elements of Element form validation in Vue

Basic elements of Element form validation in Vue

Jul 14, 2018 pm 03:52 PM

This article mainly introduces the basic elements of Element form validation in Vue. It has certain reference value. Now I share it with you. Friends in need can refer to it.

Element mainly uses async-validator This library serves as form validation

async-validatorIt is mainly divided into three parts

  • Validate

  • Options

  • Rules

Among them, Rules is the most important for us to use Element, and it is also the part with the most content.

Parts of async-validator

Basic use of async-validator

import Validator from 'async-validator'

// 规则的描述
const rules = {
  name: { type: 'string', required: true }
}

// 根据规则生成验证器
const validator = new Validator(rules)

// 要验证的数据源
const source = {
  name: 'LanTuoXie'
}

// 验证后的回调函数
function callback (errors, fileds) {
  if (errors) {
    // 验证不通过,errors是一个数组,记录那些不通过的错误信息
    // fileds是所有数据源的字段名,也即上面的source的'name'
    // 验证是根据字段名来的,rules.name 对应 source.name。 字段名要一样才会验证
  }
  // 下面是验证通过的逻辑
}

// 验证数据源是否符合规则
validator.validate(source, callback)
Copy after login

Validate

is the above The validator.validate in the example is a function

function(source, [options], callback)
Copy after login

source and callback corresponding to the above example.

Options

Options has two values ​​

  • first: A Boolean value, if present If the field does not pass, the verification of the following fields will be terminated.

  • firstFields: Boolean value or string. If a rule does not pass when validating a field, the verification of the next field will be terminated. Rules (one field, multiple rules)

firstFields is used when there are multiple rules for a single field, while first is For all fields

Rules

the most important one is Rules. Rules can be defined in three forms, but the rules field name must be consistent with the field name of the data source.

  • Function method: { name(rule, value, callback, source, options) {} }

  • Object method: { name: { type: 'string', required: true } }

  • Array method: { name: [{ type : 'string' }, { required: true }] }

As you can see above, the field name name can be defined in three ways. When using Element, it is still The object and array methods are recommended, these two are relatively simple, and the function should be used according to the situation.

In addition to type and required, what other usages can be used and what are their uses?

Default rules for Rules

  • type: The type of data to be verified such as url and number etc

  • required: Is it required?

  • pattern: Use regular expressions to Verification

  • min: Minimum value of data length (data type must be string or array)

  • max: The maximum length of data (the data type must be string or array)

  • len: The length of the data must be equal to this value (the data type must be string or array)

  • enum: The value of the data must be equal to a certain element of this enumeration array{ enum: [1, 2, 3] }

  • transform: A hook function that can process the data and then verify it before starting the verification. For example, convert number to string and then verify

  • message: The error message can be a string or a jsx tag<span>Name is required</span>

  • validator: Custom verification function and error message validator(rule, value, callback)

  • There is also a Deep Rules that handles the object or array type, using fields or defaultField

  • fields: Used when using Deep Rules to define the field names and rules of the next layer

  • defaultField: Deep Used when using Rules, all fields at the next level will adopt this rule and can be replaced by fields

Default Type

  • string: Must be of String type. If the rule does not set the type, the default is this

  • number: Must be of Number type. If the background The returned data is a string, which can be converted to Number type using transform. String type numbers ('12') will not pass. Please note that

  • boolean: Must be of Boolean type

  • method: Must be Function

  • regexp : Must be a regular RegExp

  • integer: It is a positive integer of Number type

  • float : It is a floating point number of type Number

  • array: It is the array passed by Array.isArray

  • object: Object type that Array.isArray does not pass

  • enum: Enum must be defined first, and then the value must be a certain value of enum

  • date: Must be an instance of Date object

  • url: String type and conforms to the link format

  • hex

  • ##email: String type, and conforms to the email format

Deep Rules使用demo

cosnt urls = [&#39;http://www.baidu.com&#39;, &#39;http://www.baidu.com&#39;]
// 一个urls的数组,
const rules = {
  urls: {
    type: &#39;array&#39;,
    required: true,
    defaultField: { type: &#39;url&#39; }
  }
}
Copy after login
const ids = {
  name: &#39;LanTuoXie&#39;,
  age: 12,
  spc: &#39;帅&#39;
}

const rules = {
  ids: {
    type: &#39;object&#39;,
    required: true,
    fields: {
      name: { type: &#39;string&#39;, required: true },
      age: { type: &#39;number&#39;, required: true, tranform: Number },
      spc: { type: &#39;string&#39;, required: true }
    }
  }
}
Copy after login

自定义验证validator

validator(rule, value, callback)

  • rule: 记录了验证字段的字段名以及规则的信息

  • value: 要验证的值

  • callback: 如果callback()代表验证通过,如果callback(new Error(&#39;错误要提示的信息&#39;))代表验证不通过

// 验证是[min, max]范围内的正整数
const betweenInt = (min, max) => (rule, v, cb) => {
  const isBetween = v >= min && v <= max
  const isInt = /^[0-9]+$/.test(v)
  if (isBetween && isInt) return cb()

  return cb(new Error(`要求是在${min}到${max}的正整数 [${min}, ${max}]`))
}

const rules = {
  num: { validator: betweenInt(1, 5), required: true }
}
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网! 

 相关推荐:

vue项目中如何实现保存头像以及base64字符串转图片的功能

Vue中for in对象时如何解决属性为非负整数的问题

The above is the detailed content of Basic elements of Element form validation in Vue. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles