omega
omega

Reputation: 43963

How to validate input field with JavaScript

If I have a input field with a pattern attribute for a certain regular expression, is there a JavaScript/JQuery function that can access that input DOM element, and verify if the current value in it complies with the pattern?

Upvotes: 0

Views: 2808

Answers (3)

Scott Marcus
Scott Marcus

Reputation: 65873

You will need to use the HTML5 Validity Framework (check the "Validating forms using JavaScript" section) which provides a validity object for each field that has had validation set up for it. This validity object exposes a set of "validity constraints" (one for each type of validation that HTML5 natively provides).

In your case, you'd want to check validity.patternMismatch on the element to see if it is invalid. But, when only one type of validation is applied to an element validity.valid is enough.

Below, we have a form field that is both required and has a pattern set up for it. In this case, knowing that the field is invalid may not be enough for your purposes, so the code not only tells you if the element is invalid, but shows that you can check individual constraints to know why.

Try not entering any data and clicking the submit button. That will tell you the element is invalid, but if you look at the constraint report, you will see that valueMissing = true in that case. Then try entering just a couple of characters and you'll still see it show as invalid, but the patternMismatch = true will show in that case.

var field = document.getElementById("ss");
var btn = document.getElementById("btnValidity");

btn.addEventListener("click", function(evt){

  console.clear();

  // You can test for simple validity with the valid property
  console.log("Is field valid? " + ss.validity.valid);
  
  // And, you can get more specific by checking all the validity constraints
  // Here, we're just looping the entire set for demo purposes
  for(var constraint in ss.validity){
    if(ss.validity[constraint]){
      console.log(constraint + " = " + ss.validity[constraint]);
    }
  }
  
});
/* Valid and invalid elements can show their state in real time with CSS pseudo-classes */
input[type=text]:active, input[type=text]:focus { outline:none;  }
input[type=text]:valid { box-shadow:0 0 3px green; }
input[type=text]:invalid { box-shadow:0 0 3px red; }
SS#: <input type="text" required pattern="^\d{3}-\d{2}-\d{4}$" id="ss" placeholder="xxx-xx-xxxx">
<button id="btnValidity">Check validity</button>

Upvotes: 3

hyubs
hyubs

Reputation: 737

$(function () {
    var $input = $('#my-input');  
      
    $input.on('change', function () {
        var pattern = $input.attr('data-my-pattern-attr');
        var regex = new RegExp(pattern, "g");

        if ($input.val().match(regex)) {
            console.log('matches');
        } else {
            console.log('no match');
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="my-input" data-my-pattern-attr="[a-z]+" />

Upvotes: 0

Ry-
Ry-

Reputation: 225281

HTMLInputElement.checkValidity(), supported by IE 10 and later, will check all constraints at once.

console.log(document.getElementById('a').checkValidity())
console.log(document.getElementById('b').checkValidity())
<input id="a" pattern="a+" value="aaaa" />
<input id="b" pattern="a+" value="aaba" />

Upvotes: 2

Related Questions