Bibhu
Bibhu

Reputation: 4081

How to validate a text using regular expression in java script?

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

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.

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

Upvotes: 0

Views: 153

Answers (1)

David Thomas
David Thomas

Reputation: 253486

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:

Upvotes: 3

Related Questions