tyebillion tyebillion - 3 months ago 12
Javascript Question

How to check the result of the pattern validation for a text input in Javascript?

I have a text input with a custom oninvalid message:

<input id="foo" type="text" maxlength="16" required pattern="[a-zA-Z0-9]+"
oninvalid="this.setCustomValidity('Please enter letters and /
or numbers only.')" onBlur="chk()" autofocus>


In the onBlur event I want to run some code, but only if the text entered passed the pattern validation specified. Something like:

function chk() {
if (document.getElementById("foo").isvalid?()) {
bar();
}
}


Alternatively:

function chk() {
if ($("#foo").isvalid?()) {
bar();
}
}


Update

I found the following solution, but it does repeat the code of the pattern validation:

function chk() {
var exp = /^[a-zA-Z0-9]+$/;
if (exp.test($("#foo").val())) {
bar();
}
}

Answer

You can grab the pattern from your input but we need to modify it slightly. As MDN explains: "the pattern pattern must match the entire value, not just some subset." This basically boils down to the browser implicitly prepending a ^ and appending a $ to the pattern value. So, for our case, when we grab that string pattern value from our input, we also need to do the same to match the browser's functionality:

function chk() {
  var pattern = $("#foo").attr('pattern');
  var exp = new RegExp('^' + pattern + '$');
  if (exp.test($("#foo").val())) {
    bar(); 
  }
}
Comments