Home >Web Front-end >JS Tutorial >Instant Form Validation Using JavaScript
Core points:
pattern
and required
can be used to define the valid input range of form elements. If the browser does not support these properties, its values can be used as the basis for JavaScript compatibility populators. aria-invalid
attribute can be used to indicate whether the field is invalid. This property provides accessibility information and can be used as a CSS hook to visually indicate an invalid field. instantValidation()
Test the field and perform actual verification, controlling the aria-invalid
attribute to indicate the status of the field. This function can be bound to the onchange
event to provide real-time form validation. HTML5 introduces several new properties for implementing browser-based form validation. The pattern
property is a regular expression that defines valid input ranges for text area elements and most input types. required
attribute specifies whether the field is required. For older browsers that do not support these properties, we can use their values as the basis for compatibility fillers. We can also use them to provide more interesting enhancements – real-time form validation.
It should be noted that you do not overuse verification, so as not to disrupt normal browsing behavior and hinder user operations. For example, I have seen some forms that cannot leave invalid fields using the Tab key - JavaScript is used (more precisely, abused) to force focus to stay within the field until it is valid. This is very unfavorable to the user experience and directly violates the accessibility guidelines.
This article will introduce a less invasive implementation method. It's not even full client validation - it's just a slight user experience enhancement implemented in an accessible way, and when I tested the script it found it was almost the same as Firefox's current native implementation!
Basic Concept
In the latest version of Firefox, if the required field is empty or its value does not match the pattern, the field will display a red border as shown in the following figure:
Of course, this won't happen immediately. If this happens, the border will be displayed by default for each required field. Instead, these borders are displayed only after you interact with the field, which is basically (although not exactly) similar to the onchange
event.
Therefore, we will use onchange
as the trigger event. Alternatively, we can use the oninput
event, which will fire as long as we type or paste any value in the field. But this is really too "instant" because it can easily trigger repeatedly while typing in quick succession, resulting in a flickering effect, which can get bored or distracted by some users. And, anyway, oninput
does not trigger from the programming input, and onchange
will trigger, we may need it to handle operations such as autocomplete from third-party plugins.
Define HTML and CSS
Let's take a look at our implementation, starting with the HTML it is based on:
<code class="language-html"><form action="#" method="post"> <fieldset> <legend><strong>Add your comment</strong></legend> <p> <label for="author">Name <abbr title="Required">*</abbr></label> <input aria-required="true" id="author" name="author" pattern="^([- \w\d\u00c0-\u024f]+)$" required="required" size="20" spellcheck="false" title="Your name (no special characters, diacritics are okay)" type="text" value=""> </p> <p> <label for="email">Email <abbr title="Required">*</abbr></label> <input aria-required="true" id="email" name="email" pattern="^(([-\w\d]+)(\.[-\w\d]+)*@([-\w\d]+)(\.[-\w\d]+)*(\.([a-zA-Z]{2,5}|[\d]{1,3})){1,2})$" required="required" size="30" spellcheck="false" title="Your email address" type="email" value=""> </p> <p> <label for="website">Website</label> <input id="website" name="website" pattern="^(http[s]?:\/\/)?([-\w\d]+)(\.[-\w\d]+)*(\.([a-zA-Z]{2,5}|[\d]{1,3})){1,2}(\/([-~%\.\(\)\w\d]*\/*)*(#[-\w\d]+)?)?$" size="30" spellcheck="false" title="Your website address" type="url" value=""> </p> <p> <label for="text">Comment <abbr title="Required">*</abbr></label> <textarea aria-required="true" cols="40" id="text" name="text" required="required" rows="10" spellcheck="true" title="Your comment"></textarea> </p> </fieldset> <fieldset> <input name="preview" type="submit" value="Preview"> <input name="save" type="submit" value="Submit Comment"> </fieldset> </form></code>
This example is a simple comment form where some fields are required, some fields are verified, and some fields satisfy both conditions. Fields with required
attributes also have aria-required
attributes to provide fallback semantics for assistive technologies that do not support new input types.
ARIA specification also defines the aria-invalid
attribute, which we will use to indicate if the field is invalid (there is no equivalent attribute in HTML5). The aria-invalid
property obviously provides accessibility information, but it can also be used as a CSS hook to apply red borders:
<code class="language-css">input[aria-invalid="true"], textarea[aria-invalid="true"] { border: 1px solid #f00; box-shadow: 0 0 4px 0 #f00; }</code>
We can just use box-shadow
without worrying about borders. To be honest, this will look better, but in this way, there will be no indication in browsers that do not support box-shadow
(such as IE8).
Add JavaScript
Now that we have static code, we can add scripts. First, we need a basic addEvent()
function:
<code class="language-javascript">function addEvent(node, type, callback) { if (node.addEventListener) { node.addEventListener(type, function(e) { callback(e, e.target); }, false); } else if (node.attachEvent) { node.attachEvent('on' + type, function(e) { callback(e, e.srcElement); }); } }</code>
Next, we need a function to determine whether a given field should be validated, which simply tests that it is neither disabled nor read-only, and that it has a pattern
or required
attribute:
<code class="language-javascript">function shouldBeValidated(field) { return ( !(field.getAttribute("readonly") || field.readonly) && !(field.getAttribute("disabled") || field.disabled) && (field.getAttribute("pattern") || field.getAttribute("required")) ); }</code>The first two conditions may seem verbose, but they are necessary because the
and disabled
properties of an element do not necessarily reflect their attribute state. For example, in Opera, fields with hardcoded attribute readonly
still return readonly="readonly"
for their readonly
attribute (the point attribute only matches the state set through the script). undefined
<code class="language-javascript">function instantValidation(field) { if (shouldBeValidated(field)) { var invalid = (field.getAttribute("required") && !field.value) || (field.getAttribute("pattern") && field.value && !new RegExp(field.getAttribute("pattern")).test(field.value)); if (!invalid && field.getAttribute("aria-invalid")) { field.removeAttribute("aria-invalid"); } else if (invalid && !field.getAttribute("aria-invalid")) { field.setAttribute("aria-invalid", "true"); } } }</code>Therefore, if the field is required but has no value, or it has pattern and value, but the value does not match the pattern, the field is invalid.
Since the pattern already defines the string form of the regular expression, we just need to pass the string to the
constructor, and it creates a regular expression object that we can test for that value. However, we have to pretest the value to make sure it is not empty so that the regex itself does not have to consider the empty string. RegExp
Once we have determined whether the field is invalid, we can control its aria-invalid
property to indicate the status - add it to an invalid field that does not yet have the property, or from a valid field that has the property deleted in. Very simple! Finally, in order for this to work, we need to bind the verification function to the onchange
event. It should be simple like this:
<code class="language-html"><form action="#" method="post"> <fieldset> <legend><strong>Add your comment</strong></legend> <p> <label for="author">Name <abbr title="Required">*</abbr></label> <input aria-required="true" id="author" name="author" pattern="^([- \w\d\u00c0-\u024f]+)$" required="required" size="20" spellcheck="false" title="Your name (no special characters, diacritics are okay)" type="text" value=""> </p> <p> <label for="email">Email <abbr title="Required">*</abbr></label> <input aria-required="true" id="email" name="email" pattern="^(([-\w\d]+)(\.[-\w\d]+)*@([-\w\d]+)(\.[-\w\d]+)*(\.([a-zA-Z]{2,5}|[\d]{1,3})){1,2})$" required="required" size="30" spellcheck="false" title="Your email address" type="email" value=""> </p> <p> <label for="website">Website</label> <input id="website" name="website" pattern="^(http[s]?:\/\/)?([-\w\d]+)(\.[-\w\d]+)*(\.([a-zA-Z]{2,5}|[\d]{1,3})){1,2}(\/([-~%\.\(\)\w\d]*\/*)*(#[-\w\d]+)?)?$" size="30" spellcheck="false" title="Your website address" type="url" value=""> </p> <p> <label for="text">Comment <abbr title="Required">*</abbr></label> <textarea aria-required="true" cols="40" id="text" name="text" required="required" rows="10" spellcheck="true" title="Your comment"></textarea> </p> </fieldset> <fieldset> <input name="preview" type="submit" value="Preview"> <input name="save" type="submit" value="Submit Comment"> </fieldset> </form></code>event must bubble up (using a technology commonly known as event delegate), but in Internet Explorer 8 and earlier, the
event onchange
does not occur Bubbleonchange
. We can choose to ignore these browsers, but I think it would be a shame, especially if the problem is so easy to solve. It just means that the code is a little more complex - we have to get a collection of input and text area elements, iterate through them and bind the event to each field separately:
onchange
<code class="language-css">input[aria-invalid="true"], textarea[aria-invalid="true"] { border: 1px solid #f00; box-shadow: 0 0 4px 0 #f00; }</code>Conclusion and Prospect
It's that - a simple and non-invasive real-time form verification enhancement that provides accessible and intuitive tips to help users complete forms.
After this script is implemented, we can actually complete a complete compatibility filler program in just a few steps. Such a script is beyond the scope of this article, but if you want to develop it further, all the basic modules are here-test whether the fields should be validated, the fields should be validated according to the schema and/or
, and the binding trigger event.
required
I must admit, I'm not sure if it's really worth it! If you already have this enhancement (which works in IE7 and all modern browsers), and consider that you have no choice but to implement server-side verification, and consider that you have support for
's browsers have used them for pre-submission verification - with all this in mind, is it really necessary to add another compatibility filler?
pattern
(The FAQ section about real-time verification can be added here, the content is the same as the FAQs section in the original document) required
The above is the detailed content of Instant Form Validation Using JavaScript. For more information, please follow other related articles on the PHP Chinese website!