Resurgent Resurgent - 3 months ago 9
jQuery Question

jQuery, Match and RegEx

So I have the following code in jQuery, and I am trying to essentially match dates in the format MM/YYYY where MM is a value between 1 and 12 and YYYY is a date in 1900s or 2000s. I haven't really used the jQuery test function before. Can someone tell me whats wrong with my code or the Regex?

var fieldValue = $(this).val();
if(!fieldValue.test(([1-9]|1[0-2])/^(19|20)\d\d)){
Errors = Errors + 1;
$(this).addClass("form_error");
}

Answer

You have several issues in the code:

  • You need to use RegExp#test(String), not String#test(RegExp)
  • The pattern should appear in-between regex delimiters /.../
  • The / must be escaped inside a regex literal
  • If you validate an entire string, add ^ at the start and $ anchors at the end of the pattern

Use

if(!/^(0?[1-9]|1[0-2])\/((?:19|20)\d\d)$/.test(fieldValue)) {

Else, you may use String#match and check if a match was a asuccess or not

if(fieldValue.match(/^(0?[1-9]|1[0-2])\/((?:19|20)\d\d)$/)) {

The 0? will allow an optional leading 0.

Details:

  • ^ - start of string
  • (0?[1-9]|1[0-2]) - Group 1: month, from 01 to 12
  • \/ - a /
  • ((?:19|20)\d\d) - Group 2: either 19 or 20 and then 2 digits
  • $ - end of string.
Comments