H5 uses constraints to verify the API method

This article describes how to use the H5 constraint validation API, the paper describes in great detail, it has a certain reference value, small partners who are interested must read!

HTML5 For form has a great degree of optimization, whether semantic, widget, or a data format validation. I guess you will be compatible with the browser as an excuse not to use these “new features”, but this should never be the reason for your stagnant Moreover, there ployfill such as Modernizr and tools to help you in the library is not supported rollback process on Html5 browser. When you actually try to use these forms of new features, I guarantee you will love it. If only flaw is that the prompt box is the browser’s default style, you can not change, well, if you believe the designer’s aesthetic level browser vendors, then (I believe their level of design than most ordinary people better, if you do not consider the style compatible with the case), pay close attention to just learn it!

Native verification

INPUT of type

HTML5 provides many native support for data validation format, for example:

    

when the submit button is clicked, if the format you entered does not comply with email, will result not submitted, the browser prompt you an error message.

For example, in Chrome:

H5使用约束验证API的方法

Note:

1, only when you submit will trigger verify your browser

2, different browsers prompt the behavior pattern is not the same

3, when there are multiple input does not meet the requirements, will prompt an error, the general will be prompted to form input before the relatively

deserved Do not think that when the input type is equal to tel time, if you do not enter a phone number format, at the time of submission will be the browser’s stop with an error information, type = ‘tel’ semantic functions only on the PC side, the mobile terminal can generateThe keyboard is a pure numeric keypad and does not function as a data verification.

Pattern You can use the pattern property to set custom format validation for the browser without providing native validation. The value of the PATTERN attribute is a regular expression (string):

 When you click, when you are submitted, if you enter the data you entered Do not comply with the format of the regular rules in Pattern, then the browser will prevent the form from committing, and prompt: 'Please keep the content (small word) in the requested format (small word). Note that when the content in your text box is empty, the browser will not check it, and will submit a form directly (because the browser thinks this frame is not required). If you want this box, you must have content, please add the required attribute.   With the HTML native validation system, we can basically meet the limitations of our form committed. But HTML5 provides more advanced features to facilitate our development and enhance user experience.  

By default prompt information

, please keep consistent with the requested format ‘this browse The message is hidden in the validationMessage property of the Input DOM object. This property is read-only in most modern browsers, that is, it is not modified, such as the following code:

When submitted, if the INPUT content is empty, the browser will prompt ‘Please fill in this field’, we can print this sentence in the console:
  VAR INPUT = Document.GtelementByid ('Input') Input.validationMessage // => 'Please fill in this field'   
If you want Modify the contentYou can call the SetCustomValidity interface to change the value of validationMessage

 INPUT.SETCUSTomValidity ('This field must be filled in'); // The following approach applies to a browser that does not support SetCustomValidity. Basic modern browsers do not support this input.validationMessage = 'This field must be filled in'   
Note, although the HTML native validation like Required, although it can change the information, Unable to place the information as a scroll, the reason will be described below.

   
HTML Form Verification The system detects whether the data of the text box is verified through the ValidationMessage property. If its value is a empty string, it means verified. Otherwise, the browser will prompt the user as an error message as an error message. So when you native verification, users cannot set the value of validationMessage to an empty string.

Constrained Verification API’s simple example

Constraint Verification API is a more flexible expression of the native method, you can set the data yourself, not with help In faith expressions. The principle is very simple, through the IF judgment, if the data format makes you satisfied, then you call setCustomValidity to make the value of validationMessage empty, otherwise you call setCustomValidity incorrect information:

INPUT.ADDEVENTLISTENER (‘INPUT’, FUNCTION () {if (this.Value.Length> 3) {// judgment condition completely custom input.setcustomvalidity (‘format is incorrect “;} else{INPUT.SETCUSTOMVALIDITY (”)}}); Each keyboard is entered, the code will determine if the format is correct, and then call setCustomValidity to set the value of the validationMESSAGE. Don’t want to press the button, you will prompt your result correctly, the browser only prompts the value in the validationMessage (if any) when you click the Submit button.

If you haven’t thought about it, you will be asked. In this case, why should I bind the keyboard event for the Input, every time you enter a judgment? Directly bind to the form to submit an event, and then judge how good it is, don’t worry, it is good.

With the input judgment format and style
   As a user, we certainly want to know that the text box is red (or different) after you know that I have entered the wrong format. Tip). And I entered a character every time, if it is right, the text box will return to normal. We can use CSS pseudo-class to implement this feature: 
INPUT: Required {background-color: # ffe14d;} / * This pseudo class is judged by the ValidationMessage property * / Input: Invalid {Border: 2px solid red;}

The above Required pseudo class provides a yellow background color, so the following INVALID pseudo-class will Add a 2PX red side to all INPUTs that have not passed the verification. We now add to our INPUT box.

These pseudo-class judgment conditions are in the same way as the browser determines whether you can submit a form, see ValidationMessageThe value, so we set up the keyboard input event to trigger a judgment to change the rendering of the CSS pseudo style, which is used here.

Better user experience

There is also a shortcoming, when an input is set to Required, when it is initialized, because it itself is empty, Invalid pseudo-class will work on it, this is not what we want to see, because we have nothing to do.

We can add the parent selector before these pseudo classes, so that these pseudo classes will only work only when the parent element has an InvaliD class. You can set a Submit event. After the form is submitted, the InvalID event is triggered by the Form, which is added to the Form.

form.addeventListener (‘invalid’, function () {this.classname = ‘ Invalid ‘}, true) Because Invaild is an Input event, not the Form’s event, so we set the third parameter to TRUE to use event capture. This is done.
   
Ok, now I will always sum up our knowledge we have learned and create best practices:

Form

INPUT: Required {Background-Color: # DCD4CE;} .invalid INPUT: INVALID {Border: 2px solid red;}

EMAIL:

VAR email = document.getlementByid (’email’); var idcard = document.getlementByid (‘idcard’); var Form = document.getlementByid (‘form’); idcard.addeventlistener (‘input’, function () {if (this.Value.Length! = 6) {this.setcustomvalidity (‘IDCARD must be 6’)} Else {this.SetCustomValidity (”)}}); form.addeventListener (‘invalid’, function () {this.classname = ‘invalid’;}, true)

  The screenshots were as follows:     The above is all the contents of the H5 use constraint to verify the API, thank you for reading! The content that wants to share is helpful to everyone, more related knowledge, welcome to pay attention to Tumi Yun Industry News Channel!                      
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment