You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

表单验证正则异常:合法DD/MM/YYYY格式日期无法通过JS校验

Fixing Your Date Validation Regex Issue

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 10:32:43