Element Form validation (1)

First of all, we should master Element Official examples of form validation , Then I'll see the following tutorial .

Element Mainly used async-validator This library serves as a form validation

async-validator It is mainly divided into three parts

  • Validate
  • Options
  • Rules

among , For us to use Element For the ,Rules above all , It's also more about this part .

async-validator Parts

async-validator Basic use

import Validator from 'async-validator'
// Description of rules 
const rules = {
name: { type: 'string', required: true }
} // Generate validators based on rules
const validator = new Validator(rules) // The data source to verify
const source = {
name: 'LanTuoXie'
} // The callback function after verification
function callback (errors, fileds) {
if (errors) {
// Verification failed ,errors Is an array , Record error messages that fail
// fileds Is the field name of all data sources , That is to say, the above source Of 'name'
// Validation is based on the field name ,rules.name Corresponding source.name. Field names need to be the same before validation
}
// The following is the logic of passing the verification
} // Verify that the data source complies with the rules
validator.validate(source, callback)

Validate

This is the example above validator.validate, It's a function

function(source, [options], callback)

source and callback Corresponding to the above example .

Options

Options There are two values

  • first: A Boolean value , If the field does not pass , Terminate the fields after validation
  • firstFields: Boolean values or strings , If you validate a field , One rule doesn't pass , Terminate validation next rule ( A field , The case of multiple rules )

firstFields It is used in the case of multiple rules for a single field , and first Yes, for all fields

Rules

The most important thing is Rules. Definition rule It can take three forms , however rules The field name must be the same as the data source source The field names are consistent .

  • How to function :{ name(rule, value, callback, source, options) {} }
  • How objects work : { name: { type: 'string', required: true } }
  • Array way : { name: [{ type: 'string' }, { required: true }] }

You can see up here , Field name name There can be 3 Two ways to define rules , In the use of Element It's still the way to recommend objects and arrays , These two are relatively simple , Functions are used according to the situation .

except type and required What other usages can be used and what is the use ?

Rules The default rule for

  • type: The type of data to be validated, such as url and number etc.
  • required: If required
  • pattern: Using regularization to verify
  • min: The minimum length of the data ( The data type must be string or array)
  • max: The maximum length of the 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 an element of the enumeration array { enum: [1, 2, 3] }
  • transform: A hook function , Data can be processed before validation , Like it number To string Then verify
  • message: The error message can be string or string jsx label <span>Name is required</span>
  • validator: User defined verification function and error message validator(rule, value, callback)
  • One more Deep Rules Is dealing with object perhaps array Type of , Used fields or defaultField
  • fields:Deep Rules When you use , Define the field names and rules of the next layer
  • defaultField: Deep Rules When you use , This rule is applied to all fields at the next level , Can be fields Replace

default Type

  • string: Must be String type , Rule not set type The default is this
  • number: Must be Number type , If the data returned by the background is a string , It can be used transform To Number type , String type numbers ('12') Not through , it is to be noted that
  • boolean: Must be Boolean type
  • method: Must be Function
  • regexp: It has to be regular RegExp
  • integer: yes Number A positive integer of type
  • float: yes Number Floating point number of type
  • array: yes Array.isArray Array passed
  • object: Array.isArray Not passed Object type
  • enum: You have to define enum, Then the value must be enum A certain value
  • date: Must be Date Instance of object
  • url: String Type and link format
  • hex
  • email: String type , And in line with the mailbox format

Deep Rules Use demo

cosnt urls = ['http://www.baidu.com', 'http://www.baidu.com']
// One urls Array of ,
const rules = {
urls: {
type: 'array',
required: true,
defaultField: { type: 'url' }
}
}
const ids = {
name: 'LanTuoXie',
age: 12,
spc: ' handsome '
} 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 }
}
}
}

Custom validation validator

validator(rule, value, callback)

  • rule: Record the field name of the validation field and the information of the rule
  • value: The value to verify
  • callback: If callback() Representative verification passed , If callback(new Error(' Information to prompt for errors ')) Representative verification failed
// Verify yes [min, max] Positive integer in range 
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(` The demand is in ${min} To ${max} The positive integer [${min}, ${max}]`))
} const rules = {
num: { validator: betweenInt(1, 5), required: true }
}

Element Form validation (1) More articles about

  1. Element Form validation (2)

    Element Form validation (2) The first part is about async-validator The basic elements of , that , How to use Element And how to use it gracefully , In this article . The first part talks about async-validator from 3 Most of the components ...

  2. async-validator:Element Form validation

    Reprint an article :Element Form validation (2)   Element Form validation (2) The first part is about async-validator The basic elements of , that , How to use Element And how to use it gracefully , In this article . The first part talks about a ...

  3. vue element Form validation failed , Scroll to the corresponding position

    We are using elementIUI Implement form validation , When there's a lot of content , The prompt content will be blocked , At this point, users don't know what's going on , And click the submit button in succession . It's time for demand : We need to verify the form when it doesn't pass , The page scrolls to the corresponding position . ...

  4. vue+element Form validation

    design sketch <template> <div class="formValidator"> <div v-for="(item,index) in ...

  5. Element Form validation rules

    One . Simple use of logic validation : Methods and steps : 1. stay html Middle feeding el-form increase  :rules="rules" 2.html In the el-form-item Add attributes to  prop=&qu ...

  6. Element Form validation , Do not empty data , Cancel form field validation only

    Reset form this.$refs['ageForm'].resetFields() // Form reset Clear check only this.$refs['ageForm'].clearValidate() // Clear validation

  7. solve “element The form verifies that the number entered is string” The problem of

    form Forms : Validation rules : Be careful : One . The verification of number type needs to be done in v-model Add .number The embellishment of , This is a Vue Provided by itself to convert the binding value to number Type modifier . Two . Check whether to add ...

  8. element Form validation

    rules: { name:[{ required: true, message: ' Please enter a user name ', trigger: 'blur' },{ min: 2, max: 5, message: ' length ...

  9. JS Determine string length , combination element el-input el-form Form validation ( English 1 Characters , Chinese characters account for 2 Characters )

    First of all, let's look at several ways to judge the length of a string ( English 1 Characters , Chinese characters account for 2 Characters ) Method 1 : function strlen(str) { var len = 0; for (var i = 0; i < ...

Random recommendation

  1. ABP Work after learning frame theory (Jobs) And backstage workers (Workers)

    Return to the general catalog This directory Introduce Backstage work Backstage workers Keep your app running all the time Introduce ABP Provides background work and background workers , They perform tasks in the background threads of the application . Backstage work Background work is performed in the background in a queued and continuous manner ...

  2. C/C++ sizeof Function analysis —— solve sizeof The problem of finding the size of structure

    C/C++ The amount of memory occupied by different data types in 32 position                  64 position char               1                    1 int           ...

  3. android Basic introduction to

        One .   A Communications technology   1. 1G   Voice only cellular call standard 2. 2G  ( Time division multiplexing ) Digital voice transmission technology and the function of receiving data 3. 3G   There is a big difference in the speed of transmitting sound and data promote 4. 4 ...

  4. MyEclipse build path Revise the question

  5. svg Learning notes ( One )

    SVG—— Scalable graphics , be based on XML PC End :IE9+   wap End : To perform well , Suitable for use Basic drawing : line( Line segment )  <line x1="25" y1="150 ...

  6. pycaffe︱caffe in fine-tuning Model triple sky ( Function details 、 Brief introduction of the framework )

    Main reference caffe Official documents [<Fine-tuning a Pretrained Network for Style Recognition>](http://nbviewer.jupy ...

  7. Use signalr Realtime chat between web page and WeChat official account ( On )

    Recently, customers need to be in the official account and customer service. ( The customer service uses the backstage website system ) Real time chat function . After a while , This function is realized . Now record the process , In order to have the same needs of peers can refer to , I want to make a summary myself . This is the first one , Edit with mobile phone ...

  8. Delphi XE4 For IOS How to deploy

    stay XE4 After the program is finished , How to deploy corresponding files to ios What about virtual machines and real machines ? Let's talk about . First select the project you want to deploy , choice Project->Deployment menu Deployment The menu opens as follows ...

  9. Directly modifying java Of war package

    There will be jsp Wrong feature type    descriptior UTF8  And ntfs It can be used jar Order to solve . 1. take war The package moves to a clean path , Use jar xvf ROOT.war The order will war unpack ...

  10. Wechat applet and java Background interaction

    java Used in the background ssm frame , The local interface of the applet connection . With the normal web It doesn't make any difference , It's also the background acquisition url, return json data : It's just a request from the front desk of the app url Take it with you http://localhost:80801. ...