James
James

Reputation: 135

Matching an input value with a regex in Javascript

I am trying to validate a regex pattern against the input of a field with JS.

My code is:

<script>

function expiry_check(){
var y;
y = document.getElementById("expiry_date").value;
var x;
x = /(0[1-9]|10|11|12)/(18|19|20|21|22|23|24|25|26)/;
if (y !== "") {
  if (x.test(y))  {


  }

  else {

    document.getElementById('expiry_date').value = '';
    document.getElementById('expiry_date').style = 'border-color:red';

  }

 }

}

</script>

And the HTML field:

<input type="text" name="expiry_date" id="expiry_date" value="" onkeypress='return event.charCode >= 48 && event.charCode <= 57' onblur="expiry_check()">

For some reason, the regex works if applied as a "pattern" attribute, but I need to do it with Javascript, and it doesn't work when specified as JS code.

What am I doing wrong? I've tested the same function with a different regex string, and it works fine - so the issue is with the regex itself.

Upvotes: 5

Views: 12194

Answers (2)

nrg
nrg

Reputation: 518

You should escape the '/' character.

Try this:

x = /(0[1-9]|10|11|12)\/(18|19|20|21|22|23|24|25|26)/;

Alternatively, you can create the RegExp instance from a string:

x = new RegExp('(0[1-9]|10|11|12)/(18|19|20|21|22|23|24|25|26)');

Upvotes: 4

Marventus
Marventus

Reputation: 874

You need to create an actual RegEx out of your x variable so it can be recognized as such by .test(): var x = /(0[1-9]|10|11|12)/(18|19|20|21|22|23|24|25|26)/;

var testX = new RegExp(x);
if (y !== "") {
    if (testX.test(y)){
        // Match
    } else {
        // No match
    }
}

Upvotes: 1

Related Questions