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!

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.


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

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
