5

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.

2 Answers 2

4

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)');
Sign up to request clarification or add additional context in comments.

1 Comment

You were right - didn't know I had to escape it :) Works like a charm now! Thank you!
1

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
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.