如何在java脚本中使用正则表达式验证文本?

时间:2021-09-14 00:18:05

I have a regular expression to validate the dates and it works fine, this is it

我有一个正则表达式来验证日期,它工作正常,就是这样

^(0[1-9]|[1-9]|1[012])[- /.](0[1-9]|[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$

But I want to validate it using the javascript. I tried with this

但我想用javascript验证它。我试过这个

var  ck_effectivedate= /^(0[1-9]|[1-9]|1[012])[- /.](0[1-9]|[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$/;

function radtxtbxNewEffectiveDateOnBlur(sender, eventArgs) {

  if (!ck_effectivedate.test(sender.get_value())) {
    alert('matches');
   }
   else
   {
     alert('does not match');
   }

}

But, the regular expression is not working, because of the presence of / character in my regular expression which is also used to encapsulate the regular expression in java script.

但是,正则表达式不起作用,因为我的正则表达式中存在/字符,它也用于在java脚本中封装正则表达式。

If I remove the / character then it works, but I want to use that in my string. Please help.

如果我删除/字符然后它工作,但我想在我的字符串中使用它。请帮忙。

1 个解决方案

#1


3  

You simply need to escape the special characters with a backslash \:

您只需要使用反斜杠\来转义特殊字符:

^(0[1-9]|[1-9]|1[012])[- \/.](0[1-9]|[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d$

References:

参考文献:

#1


3  

You simply need to escape the special characters with a backslash \:

您只需要使用反斜杠\来转义特殊字符:

^(0[1-9]|[1-9]|1[012])[- \/.](0[1-9]|[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d$

References:

参考文献: