BforBellyRub
BforBellyRub

Reputation: 13

`.checkValidity()` with the HTML5 `pattern` attribute always returns true

I’m using the below code snippet to check the validity of this input to make sure it does not contain any commas:

var valid_part = document.getElementById("part");

if (valid_part.checkValidity()) {
  alert("Item Description contains no commas ");
}
else {
  alert("Item Description cannot contain a comma");
}
<input pattern="[^,]" type="text" id="part">

However, valid_part.checkValidity() always returns true no matter what the input value is.

I’ve tried this on Chromium and Firefox on Debian, and Chrome and Firefox on Android and the result is always the same.

Is the function valid? If not, should I use an alternate method to check for commas in the input?

Upvotes: 0

Views: 4143

Answers (1)

Sebastian Simon
Sebastian Simon

Reputation: 19525

From the MDN documentation for <input> (emphasis mine):

pattern: A regular expression that the control’s value is checked against. The pattern must match the entire value.

Thus, [^,] means “the string contains exactly one character that isn’t a comma”. So your validation check should actually return true only for single characters except ,. It also returns true for the empty string, but it actually returns false for all other strings.

You want [^,]* which means “the string contains any number of characters (including none) that aren’t commas”.

Also, it wasn’t clear from the code you provided, but make sure that that code is in a function that runs when you need the validation. Example snippet:

document.getElementById("checker").addEventListener("click", function() {
  var valid_part = document.getElementById("part");

  if (valid_part.checkValidity()) {
    alert("Item Description contains no commas ");
  }
  else {
    alert("Item Description cannot contain a comma");
  }
});
<input id="part" type="text" pattern="[^,]*" />
<input id="checker" type="button" value="Check validity" />

Upvotes: 3

Related Questions