表单验证正则异常:合法DD/MM/YYYY格式日期无法通过JS校验
Hey there, I see exactly why your date regex isn't working—this is a classic JavaScript string escaping gotcha with the RegExp constructor! Let's break it down:
The Root Problem
When you create a regex using new RegExp("pattern string"), JavaScript first parses the string itself. Any backslash (\) in your pattern gets treated as a string escape character, not part of the regex syntax.
Your current date pattern:
var pattern3 = new RegExp("^\d{2}[\/]\d{2}[\/]\d{4}$");
Gets silently mangled by the JavaScript string engine into this actual regex:
^d{2}[/]d{2}[/]d{4}$
Instead of looking for digits (\d), it's searching for the letter d—that's why valid dates like 02/02/2020 are failing the test!
Two Simple Fixes
1. Use a Regex Literal (Recommended)
Regex literals skip the string parsing step, so you don't need extra escaping. This is cleaner and less error-prone:
var pattern3 = /^\d{2}\/\d{2}\/\d{4}$/;
2. Double-Escape Backslashes in the String
If you need to stick with the RegExp constructor, escape every backslash with another backslash to make sure it reaches the regex engine:
var pattern3 = new RegExp("^\\d{2}\\/\\d{2}\\/\\d{4}$");
Why the Alert Showed the Correct Date
The alert(dop) works because you're directly outputting the user's raw input value—this has nothing to do with the regex parsing issue. The regex itself was just checking for the wrong pattern behind the scenes.
Once you fix the regex, your date validation will start working as expected, and you'll trigger that alert('OK') for valid DD/MM/YYYY dates.
内容的提问来源于stack exchange,提问作者Anseur

