最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Matching an input value with a regex in Javascript - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Jan 10, 2018 at 12:54 JamesJames 1352 gold badges3 silver badges11 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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)');

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
    }
}
发布评论

评论列表(0)

  1. 暂无评论