[英]JavaScript regular expression to match mm/dd/yyyy format - restrict to numeric input only
我正在嘗試編寫一些正則表達式來驗證MM / DD / YYYY日期輸入。 日期的每個部分都是一個單獨的輸入文本字段,由“ /”分隔,例如:
1985年 1 月16 日
日期為1985年1月16日。
我現在在只允許數字輸入的地方使用它,使用replace()和簡單的正則表達式很容易。 順便說一句,正則表達式不是我的強項,我沒有做太多,也許每兩年一次或兩次。
下面是我正在使用的代碼以及我的replace()下面的一些psuedo-regex。 我很難將數字輸入正則表達式與我要實現的日期格式正則表達式綁定在一起(在replace()下注釋)
//MM
$(this).keyup(function() {
//allow only numbers
this.value = this.value.replace(/[^0-9]/g, '');
//(0[1-9]|1[012])
//matching 01 (Jan) to 09 (Sep) to 10 (Oct) to 12 (Dec)
});
//DD
$(this).keyup(function() {
//allow only numbers
this.value = this.value.replace(/[^0-9]/g, '');
//(0[1-9]|[12][0-9]|3[01])
//matching 01-09, 10-19, 20-29, 30-31
//(not worried about picking 31 in February)
});
//YYYY
$(this).keyup(function() {
//allow only numbers
this.value = this.value.replace(/[^0-9]/g, '');
//(\d{4})
//really simple 4 digit, but don't really want 1245 as a valid year
//a range from 1900-current year would be great
//( 1900-newDate().getFullYear() )
//something like this possible?
);
(?:0[1-9]|1[0-2])/(?:0[1-9]|[12][0-9]|3[01])/(?:19|20)[0-9]{2}
(?:text)
防止反向引用,請刪除?:
如果需要) /
-> \\/
三個不同的字段只是拆分的問題, /
是分隔符。
天(01至31)
0[1-9]|[12][0-9]|3[01]
月(01至12)
0[1-9]|1[0-2]
年(1900-2099)
(?:19|20)[0-9]{2}
您最好對/進行拆分,然后測試所有單個部分。 但是,如果您真的想使用正則表達式,可以嘗試以下一種:
#^(?:(?:(?:(?:0?[13578])|(1[02]))/31/(19|20)?\d\d)|(?:(?:(?:0?[13-9])|(?:1[0-2]))/(?:29|30)/(?:19|20)?\d\d)|(?:0?2/29/(?:19|20)(?:(?:[02468][048])|(?:[13579][26])))|(?:(?:(?:0?[1-9])|(?:1[0-2]))/(?:(?:0?[1-9])|(?:1\d)|(?:2[0-8]))/(?:19|20)?\d\d))$#
說明:
^ # start of line
(?: # group without capture
# that match 31st of month 1,3,5,7,8,10,12
(?: # group without capture
(?: # group without capture
(?: # group without capture
0? # number 0 optionnal
[13578] # one digit either 1,3,5,7 or 8
) # end group
| # alternative
(1[02]) # 1 followed by 0,1 or 2
) # end group
/ # dash
31 # number 31
/ # dash
(19|20)? #numbers 19 or 20 optionnal
\d\d # 2 digits from 00 to 99
) # end group
|
(?:(?:(?:0?[13-9])|(?:1[0-2]))/(?:29|30)/(?:19|20)?\d\d)
|
(?:0?2/29/(?:19|20)(?:(?:[02468][048])|(?:[13579][26])))
|
(?:(?:(?:0?[1-9])|(?:1[0-2]))/(?:(?:0?[1-9])|(?:1\d)|(?:2[0-8]))/(?:19|20)?\d\d)
)
$
我已經解釋了第一部分,其余部分留作練習。
此匹配一個無效日期:02/29/1900,但對於01/01/1900到12/31/2099之間的任何其他日期都是正確的
您想要的日期格式的正則表達式應該是這樣的
[0-9]{2}/[0-9]{2}/[0-9]{4}
這應該工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.