ValidityState: patternMismatch property
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The read-onlypatternMismatch property of theValidityState interface indicates if the value of an<input>, after having been edited by the user, does not conform to the constraints set by the element'spattern attribute.
ThepatternMismatch property will be true if and only if the following conditions are all true:
In this article
Value
A boolean that istrue if theValidityState object does not conform to the constraints.
Examples
Given the following:
<p> <label >Enter your phone number in the format (123)456-7890 (<input name="tel1" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit area code" size="2" />)- <input name="tel2" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit prefix" size="2" /> - <input name="tel3" type="tel" pattern="[0-9]{4}" placeholder="####" aria-label="4-digit number" size="3" /> </label></p>Here we have 3 sections for a North American phone number with an implicit label encompassing all three components of the phone number, expecting 3-digits, 3-digits and 4-digits respectively, as defined by thepattern attribute set on each.
If the values are too long or too short, or contain characters that aren't digits,patternMismatch will be true. Whentrue, the element matches the:invalid CSS pseudo-classes.
input:invalid { border: red solid 3px;}Note, in this case, we get apatternMismatch not avalidityState.tooLong orvalidityState.tooShort if the values are too long or too short because it is the pattern that is dictating the length of the value. Had we usedminlength andmaxlength attributes instead, we may have seenvalidityState.tooLong orvalidityState.tooShort being true.
Note:Theemail input type requires, at minimum, a match ofx@y and theurl type requires, at minimum, a match to x:, with no pattern attribute present. When invalid, thevalidityState.typeMismatch will be true, if there is no pattern attribute (or if the pattern attribute is not valid for that input type).
Specifications
| Specification |
|---|
| HTML> # dom-validitystate-patternmismatch> |