A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.cdn.mozilla.net/en-US/docs/Web/API/ValidityState/customError below:

ValidityState: customError property - Web APIs

ValidityState: customError property

Baseline Widely available

The read-only customError property of the ValidityState interface returns true if an element doesn't meet the validation required in the custom validity set by the element's setCustomValidity() method.

Value

A boolean that is true if a custom error message has been set to a non-empty string.

Examples Detecting a custom error

In this example, setCustomValidity() sets a custom error message when a form submission contains user input that's considered invalid. The "Validate input" button calls reportValidity(), which displays a validation message under the element if a user enters values that do not match the form's constraints.

If you enter the text "good" or "fine" and try to validate the input, the field is marked invalid until the custom error message is cleared (set to an empty string). For comparison, there is a minlength attribute on the input element that allows us to demonstrate the tooShort validity state when the user enters less than two characters. When the value in the form control is invalid, even if there is no custom error, the input will have a red outline.

HTML
<pre id="log">Validation failures logged here...</pre>
<input
  type="text"
  id="userInput"
  placeholder="How do you feel?"
  minlength="2" />
<button id="checkButton">Validate input</button>
CSS
input:invalid {
  border: red solid 3px;
}
body {
  margin: 0.5rem;
}
pre {
  padding: 1rem;
  height: 2rem;
  background-color: lightgrey;
  outline: 1px solid grey;
}
JavaScript
const userInput = document.getElementById("userInput");
const checkButton = document.getElementById("checkButton");
const logElement = document.getElementById("log");

function log(text) {
  logElement.innerText = text;
}

const check = (input) => {
  // Handle cases where input is too vague
  if (input.value === "good" || input.value === "fine") {
    input.setCustomValidity(`"${input.value}" is not a feeling.`);
  } else {
    // An empty string resets the custom validity state
    input.setCustomValidity("");
  }
};

userInput.addEventListener("input", () => {
  check(userInput);
});

const validateInput = () => {
  userInput.reportValidity();
  if (userInput.validity.customError) {
    // We can handle custom validity states here
    log(`Custom validity error: ${userInput.validationMessage}`);
  } else {
    log(userInput.validationMessage);
  }
};

checkButton.addEventListener("click", validateInput);
Result Specifications Browser compatibility See also

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4