gornvix
gornvix

Reputation: 3374

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(); 
    }
}

Upvotes: 2

Views: 2746

Answers (4)

rgthree
rgthree

Reputation: 7273

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(); 
  }
}

Upvotes: 1

&#193;lvaro
&#193;lvaro

Reputation: 2069

You don't need to recheck if the text matches the regular expression manually. You can just check the ValidityState.

function chk() {
    if ($("#foo").validity.valid) {
        bar(); 
    }
}

Upvotes: 4

Gatsbill
Gatsbill

Reputation: 1790

first of all you want to create a regex with the pattern attribute you set in your input :

function chk() {

     var pattern = this.getAttribute('pattern');
     var regex = new RegExp(pattern);

     // ...  
} 

and then verify if the input value match the regex :

function chk() {

     var pattern = this.getAttribute('pattern');
     var regex = new RegExp(pattern);

     // regex matching
     if (regex.test(this.value)) {
       bar();
     }

}

see this fiddle: https://jsfiddle.net/t6wLeqq0/1/

Upvotes: 1

Rafi Ud Daula Refat
Rafi Ud Daula Refat

Reputation: 2257

you can check onChange event and call that method everytime an input is changed

Upvotes: 1

Related Questions