search
HomeWeb Front-endJS TutorialInstant Form Validation Using JavaScript

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>

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;
}

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

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");
    }
  }
}
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>
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.

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
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
The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

See all articles

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.