Table of Contents
Real-time form verification: subtle improvements to enhance user experience
Home Web Front-end JS Tutorial Instant Form Validation Using JavaScript

Instant Form Validation Using JavaScript

Feb 16, 2025 am 10:40 AM

Real-time form verification: subtle improvements to enhance user experience

Instant Form Validation Using JavaScript

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 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.
  • 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 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:

Instant Form Validation Using JavaScript

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>
Copy after login
Copy after login

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.

The

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;
}
Copy after login
Copy after login

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);
    });
  }
}
Copy after login

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"))
  );
}
Copy after login
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

Once we have these utilities we can define the main validation function, which tests the field, and then performs the actual validation as needed:

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");
    }
  }
}
Copy after login
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:

However, in order for this to work, the
<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>
Copy after login
Copy after login
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;
}
Copy after login
Copy after login
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.

requiredI 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

And

'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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles