5

I'm currently using this RegEx ^(0[1-9]|1[0-2])/(19|2[0-1])\d{2}$ in .NET to validate a field with Month and Year (12/2000).

I'm changing all my RegEx validations to JavaScript and I'm facing an issue with this one because of /in the middle which I'm having problems escaping.

So based on other answers in SO I tried:

    RegExp.quote = function (str) {
        return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
    };
    var reDOB = '^(0[1-9]|1[0-2])/(19|2[0-1])\d{2}$'

            var re = new RegExp(RegExp.quote(reDOB));
            if (!re.test(args.Value)) {
                args.IsValid = false;
                return;
            }

However, validations fails even with valid data.

7
  • 1
    How about just a simple var re = /^(0[1-9]|1[0-2])\/(19|2[0-1])\d{2}$/; which uses the regex operator // ?? Commented Jun 10, 2015 at 23:39
  • @sln Isn't that a regex literal? Commented Jun 10, 2015 at 23:41
  • Oh, maybe. Doesn't it compile re there as a regex object ? Commented Jun 10, 2015 at 23:42
  • Sort of like a variant maybe var re = /.../; regex object, as opposed to var s = '...'; bstr object. Commented Jun 10, 2015 at 23:48
  • 1
    @Diomedes—for single digit months, remove the leading zero: /^([1-9]|1[0-2])\/(19|2[0-1])\d{2}$/ Commented Jun 11, 2015 at 0:14

1 Answer 1

1

Remove ^ of first and $ from end of regex pattern. And add \ before any character which you want to match by pattern. so pattern is like this:

(0[1-9]|1[0-2])\/(19|2[0-1])\d{2}

You can test your regex from here

Sign up to request clarification or add additional context in comments.

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.