Basic elements of Element form validation in Vue
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-validator
It 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)
Validate
is the above The validator.validate in the example is a function
function(source, [options], callback)
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 asurl
andnumber
etcrequired
: Is it required?pattern
: Use regular expressions to Verificationmin
: Minimum value of data length (data type must bestring
orarray
)max
: The maximum length of data (the data type must bestring
orarray
)len
: The length of the data must be equal to this value (the data type must bestring
orarray
)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, convertnumber
tostring
and then verifymessage
: The error message can be a string or a jsx tag<span>Name is required</span>
validator
: Custom verification function and error messagevalidator(rule, value, callback)
There is also a Deep Rules that handles the
object
orarray
type, usingfields
ordefaultField
fields
: Used when using Deep Rules to define the field names and rules of the next layerdefaultField
: Deep Used when using Rules, all fields at the next level will adopt this rule and can be replaced byfields
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 usingtransform
. String type numbers ('12') will not pass. Please note thatboolean
: Must be of Boolean typemethod
: Must be Functionregexp
: Must be a regular RegExpinteger
: It is a positive integer of Number typefloat
: It is a floating point number of type Numberarray
: It is the array passed by Array.isArrayobject
: Object type that Array.isArray does not passenum
: Enum must be defined first, and then the value must be a certain value of enumdate
: Must be an instance of Date objecturl
: String type and conforms to the link formathex
##email
: String type, and conforms to the email format
Deep Rules使用demo
cosnt urls = ['http://www.baidu.com', 'http://www.baidu.com'] // 一个urls的数组, const rules = { urls: { type: 'array', required: true, defaultField: { type: 'url' } } }
const ids = { name: 'LanTuoXie', age: 12, spc: '帅' } const rules = { ids: { type: 'object', required: true, fields: { name: { type: 'string', required: true }, age: { type: 'number', required: true, tranform: Number }, spc: { type: 'string', required: true } } } }
自定义验证validator
validator(rule, value, callback)
rule
: 记录了验证字段的字段名以及规则的信息value
: 要验证的值callback
: 如果callback()
代表验证通过,如果callback(new Error('错误要提示的信息'))
代表验证不通过
// 验证是[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 } }
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
vue项目中如何实现保存头像以及base64字符串转图片的功能
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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...

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.

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 in JavaScript? When processing data, we often encounter the need to have the same ID...

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.

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/)...

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 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.
