Real-time form verification: subtle improvements to enhance user experience
Core points:
- JavaScript can be used to implement real-time form verification, which provides users with instant feedback on input validity, thereby improving user experience and maintaining data integrity, ensuring that only valid data is submitted.
- HTML5 attributes
pattern
andrequired
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.
The -
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. - JavaScript function
instantValidation()
Test the field and perform actual verification, controlling thearia-invalid
attribute to indicate the status of the field. This function can be bound to theonchange
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:
<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>
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:
input[aria-invalid="true"], textarea[aria-invalid="true"] { border: 1px solid #f00; box-shadow: 0 0 4px 0 #f00; }
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:
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); }); } }
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:
function shouldBeValidated(field) { return ( !(field.getAttribute("readonly") || field.readonly) && !(field.getAttribute("disabled") || field.disabled) && (field.getAttribute("pattern") || field.getAttribute("required")) ); }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
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"); } } }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:
<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>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
input[aria-invalid="true"], textarea[aria-invalid="true"] { border: 1px solid #f00; box-shadow: 0 0 4px 0 #f00; }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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)
