• Skip to main content
  • Skip to search
  • Skip to select language
MDN Web Docs
  • References
    • Overview / Web Technology

      Web technology reference for developers

    • HTML

      Structure of content on the web

    • CSS

      Code used to describe document style

    • JavaScript

      General-purpose scripting language

    • HTTP

      Protocol for transmitting web resources

    • Web APIs

      Interfaces for building web applications

    • Web Extensions

      Developing extensions for web browsers

    • Accessibility

      Build web projects usable for all

    • Web Technology

      Web technology reference for developers

  • Learn
    • Overview / MDN Learning Area

      Learn web development

    • MDN Learning Area

      Learn web development

    • HTML

      Learn to structure web content with HTML

    • CSS

      Learn to style content using CSS

    • JavaScript

      Learn to run scripts in the browser

    • Accessibility

      Learn to make the web accessible to all

  • Plus
    • Overview

      A customized MDN experience

    • AI Help

      Get real-time assistance and support

    • Updates

      All browser compatibility updates at a glance

    • Documentation

      Learn how to use MDN Plus

    • FAQ

      Frequently asked questions about MDN Plus

  • Curriculum New
  • Blog
    • Playground

      Write, test and share your code

    • HTTP Observatory

      Scan a website for free

    • AI Help

      Get real-time assistance and support

  • Log in
  • Sign up for free
  1. References
  2. HTML
  3. Guides
  4. Constraint validation
    • Deutsch
    • Français
    • 日本語
    • Русский
    • 中文 (简体)

In this article

  • Intrinsic and basic constraints
  • Constraint validation process
  • Complex constraints using the Constraint Validation API
  • Visual styling of constraint validation
  1. HTML
  2. Guides
  3. Content categories
  4. Comments
  5. Date and time formats
  6. Constraint validation
  7. Viewport meta element
  8. Responsive images
  9. Microdata
  10. Microformats
  11. Quirks and standards modes
  12. HTML cheatsheet
  13. How to
  14. Define terms with HTML
  15. Use data attributes
  16. Use cross-origin images
  17. Add a hitmap on top of an image
  18. Author fast-loading HTML pages
  19. Add JavaScript
  20. Reference
  21. Elements
    1. Deprecated
    2. Deprecated

    3. Deprecated
    4. Deprecated
    5. Experimental
    6. Deprecated
    7. Deprecated
    8. Deprecated

First, we write a function checking the constraint itself:

js
function checkPostalCode() {
  // For each country, defines the pattern that the postal code has to follow
  const constraints = {
    ch: [
      "^(CH-)?\\d{4}$",
      "Swiss postal codes must have exactly 4 digits: e.g. CH-1950 or 1950",
    ],
    fr: [
      "^(F-)?\\d{5}$",
      "French postal codes must have exactly 5 digits: e.g. F-75012 or 75012",
    ],
    de: [
      "^(D-)?\\d{5}$",
      "German postal codes must have exactly 5 digits: e.g. D-12345 or 12345",
    ],
    nl: [
      "^(NL-)?\\d{4}\\s*([A-RT-Z][A-Z]|S[BCE-RT-Z])$",
      "Dutch postal codes must have exactly 4 digits, followed by 2 letters except SA, SD and SS",
    ],
  };

  // Read the country id
  const country = document.getElementById("country").value;

  // Get the NPA field
  const postalCodeField = document.getElementById("postal-code");

  // Build the constraint checker
  const constraint = new RegExp(constraints[country][0], "");
  console.log(constraint);

  // Check it!
  if (constraint.test(postalCodeField.value)) {
    // The postal code follows the constraint, we use the ConstraintAPI to tell it
    postalCodeField.setCustomValidity("");
  } else {
    // The postal code doesn't follow the constraint, we use the ConstraintAPI to
    // give a message about the format required for this country
    postalCodeField.setCustomValidity(constraints[country][1]);
  }
}

Then we link it to the onchange event for the :

js
window.onload = () => {
  document.getElementById("country").onchange = checkPostalCode;
  document.getElementById("postal-code").oninput = checkPostalCode;
};

Limiting the size of a file before its upload

Another common constraint is to limit the size of a file to be uploaded. Checking this on the client side before the file is transmitted to the server requires combining the Constraint Validation API, and especially the field.setCustomValidity() method, with another JavaScript API, here the File API.

Here is the HTML part:

html


This displays:

The JavaScript reads the file selected, uses the File.size() method to get its size, compares it to the (hard coded) limit, and calls the Constraint API to inform the browser if there is a violation:

js
function checkFileSize() {
  const fs = document.getElementById("fs");
  const files = fs.files;

  // If there is (at least) one file selected
  if (files.length > 0) {
    if (files[0].size > 75 * 1000) {
      // Check the constraint
      fs.setCustomValidity("The selected file must not be larger than 75 kB");
      fs.reportValidity();
      return;
    }
  }
  // No custom constraint violation
  fs.setCustomValidity("");
}

Finally, we hook the method with the correct event:

js
window.onload = () => {
  document.getElementById("fs").onchange = checkFileSize;
};

Visual styling of constraint validation

Apart from setting constraints, web developers want to control what messages are displayed to the users and how they are styled.

Controlling the look of elements

The look of elements can be controlled via CSS pseudo-classes.

:required and :optional CSS pseudo-classes

The :required and :optional pseudo-classes allow writing selectors that match form elements that have the required attribute, or that don't have it.

:placeholder-shown CSS pseudo-class

See :placeholder-shown.

:valid :invalid CSS pseudo-classes

The :valid and :invalid pseudo-classes are used to represent elements whose content validates and fails to validate respectively according to the input's type setting. These classes allow the user to style valid or invalid form elements to make it easier to identify elements that are either formatted correctly or incorrectly.

Controlling the text of constraint violation

The following items can help with controlling the text of a constraint violation:

  • The setCustomValidity(message) method on the following elements:

    • . Note: Setting a custom validity message on fieldset elements will not prevent form submission in most browsers.