Detailed introduction of native JS validation methods and attributes of form such as checkValidity

First, start with the external performance of the built-in verification of the form

Speaking of form built-in validation, many people think of setting requiredsuch HTML attributes, and then there will be such a prompt effect when the form is submitted:

Form built-in prompt effect

In fact, this is just a representation, just a small part of the native validation of the form. The essence of form built-in verification is more than just superficial things.

CSS, for example, has many side matching pseudo-classes, such as :requiredpseudo-classes,  :optionalpseudo-classes or :valid, :invalidpseudo the like.

Another example is the JS DOM event, which can monitor 'invalid'and 'valid'event form elements .

Another example is JS DOM API, which has many built-in verification methods and attributes. This is the knowledge point to be introduced in this article.

Two, form form element built-in verification methods and attributes

There are 3 methods and 1 attribute in total.

Three methods are checkValidity()reportValidity()setCustomValidity()method, an attribute is a validityproperty.

details as follows:

checkValidity() method

checkValidity()The method can be used to verify the current form control element, or whether the entire form is verified, the return value is a Boolean value, trueor false.

For example, whether a drop-down box element is verified:

var isSelectPassing = document.querySelector('select').checkValidity();    // true或false

Validation of drop-down box elements

Or whether the entire form element is validated:

var isFormPassing = document.forms[0].checkValidity();    // true或false

The form element calls the verification method

reportValidity() method

reportValidity()The method can trigger the browser's built-in verification prompt interaction, return a Boolean value, trueor false. E.g:

document.querySelector('select').reportValidity()

Will trigger the error prompt of the drop-down box, as shown in the following figure:

Drop-down box verification prompt triggered

In addition, the reportValidity()method IE browser does not support, Edge 17+ began to support.

setCustomValidity() method

As the name implies, it is to set a custom verification, we can use this method to customize the prompt text.

The syntax is as follows:

ele.setCustomValidity (p);

Among them, stris a string, which means the text information of the error message, if it is an empty string, it means that the custom error message is not used.

For example, reportValidity()the drop-down error message of the above method is "Please select one item in the list".

If we want to change to "Please select a city", we can do the following:

var eleSelect = document.querySelector('select'); 
if (eleSelect.validity.valueMissing == true) { 
    eleSelect.setCustomValidity('Please select a city'); 
} 
eleSelect.reportValidity();

At this point, the prompt effect is:

Change the prompt copy information

Validity property and ValidityState object

Every standard form control, such as input boxes, drop-down boxes, and single check boxes, has a built-in validityproperty, which is a read-only property that can return various validation states of the current element, for example:

console.dir(document.querySelector('select').validity);

The result returned under the Chrome browser is a ValidityState object, which contains attributes and attribute values ​​as follows:

badInput: false
customError: false
patternMismatch: false
rangeOverflow: false
rangeUnderflow: false
stepMismatch: false
tooLong: false
tooShort: false
typeMismatch: false
valid: false
valueMissing: true

The screenshot of the console output is as follows:

Built-in verification status object

among them

badInput

Read only. The attribute value is of Boolean type. The value browser in the input box cannot be converted. For example, 'number'the type of which is the Chinese character input box (on MDN statement, but the test can not reproduce themselves), then the value is true. This attribute is not supported by Internet Explorer. It is recommended to understand this attribute.

customError

Read only. The attribute value is of Boolean type. If the element call setCustomValidity()method is set with custom authentication information, the value is yes true.

patternMismatch

Read only. The attribute value is of Boolean type. The patternvalue is when it does not match the specified regular attribute value true. Will match :invalidthis CSS pseudo-class.

rangeOverflow

Read only. The attribute value is of Boolean type. It maxwill be when the value set by the attribute is exceeded true. It will also match CSS  :invalidand :out-of-rangepseudo-classes.

rangeUnderflow

Read only. The attribute value is of Boolean type. It minwill be when it is less than the value set by the property true. It will also match CSS  :invalidand :out-of-rangepseudo-classes.

stepMismatch

Read only. The attribute value is of Boolean type. When the current value of the input box stepdoes not match the attribute value, stepMismatchthe value will be true. At the same time, the elements will match CSS  :invalidand :out-of-rangepseudo-classes.

tooLong

Read only. The attribute value is of Boolean type. It maxlengthwill be when the length of the input content exceeds the limit true. It will also match CSS  :invalidand :out-of-rangepseudo-classes.

tooShort

Read only. The attribute value is of Boolean type. When the length of minlengththe input content is insufficient , it will be true. It will also match CSS  :invalidand :out-of-rangepseudo-classes. This attribute is not supported by Internet Explorer because it does not support the minlengthattribute.

typeMismatch

Read only. The attribute value is of Boolean type. When the value of the input box does not match the type of the input box, the attribute value will be true. For example, when the input box type is email or url. If the value is yes true, it will match :invalidthis CSS pseudo-class.

valid

Read only. The attribute value is of Boolean type. The current element is fully validated by Shi truewill match :validthe CSS pseudo-classes; not by Shi falsewill match :invalidthe CSS pseudo-classes.

valueMissing

Read only. The attribute value is of Boolean type. If the element has an requiredattribute set and the value of the input box is empty, the attribute value is true. If the value is yes true, it will match :invalidthis CSS pseudo-class.

Three, IE9 browser polyfill

All of the above native form verification methods and attributes are not supported by IE9 browsers, but both IE10+ browsers.

Form native verification method compatibility

If you want IE9 browser to support it, you need to write a polyfill. I probably searched, checkValidity()and there are no suitable polyfills for a few methods. Some of the existing projects are compatible with IE8, which are more like shim, and are not specifically built for IE9. polyfill.

However, the validity attribute found a polyfill that looked a little reliable. You can click here (right-click → save as): validity-polyfill.js . This polyfill comes from here , but I have not carefully verified its correctness.

Later, I will checkValidity()fill in several methods for IE9 browser .

Four, write and write become a document

I thought that I would find some interesting things at the point of this article, such as custom form validation logic. Later I found out that I was thinking too much. The setCustomValidity()method is not as powerful as I expected. It is a method to change the prompt text information.

After sorting it out, it became a more detailed document about native validation of forms.

After writing the verification component, I will use these native built-in verification methods to achieve it, which can save a lot of effort and will be very interesting.

The wonderful performance in the future comes from the usual accumulation.

For most people, these APIs in this article are insensible. I can't think of how to apply them in actual projects. I feel very tasteless. In fact, there is a lot to do. I already want to try it, hehe.

Guess you like

Origin blog.csdn.net/lu92649264/article/details/112798977