你不需要使用正則表達式,使用DateTime.TryParse
或DateTime.TryParseExact
代替。我建議使用常規的TryParse
方法,因爲它爲您的訪問者提供其格式的靈活性(例如,某些訪問者可能想要使用24小時系統,而其他人可以使用12小時系統)。
String input;
DateTime dt;
if(!DateTime.TryParse(input, CultureInfo.InvariantCulture /* change if appropriate */, DateTimeStyles.None, out dt)) {
// show error message
}
現在,當你使用一個校驗器,你要結束這一邏輯在Validator
子類,但它真的很簡單:
public class DateTimeValidator : BaseValidator {
protected override bool EvaluateIsValid() {
String controlValidationValue = base.GetControlValidationValue(base.ControlToValidate);
if(String.IsNullOrEmpty(controlValidationValue)) return true;
DateTime dt;
return DateTime.TryParse(input, CultureInfo.InvariantCulture /* change if appropriate */, DateTimeStyles.None, out dt);
}
}
然後(假設您已註冊標籤前綴web.config
)所有你需要做的是這樣的:
<label>
Enter a valid date/time value.
<input type="text" runat="server" id="someDate" />
<myprefix:DateTimeValidator runat="server" controlToValidate="someDate" />
</label>
您將需要一個單獨的<asp:RequiredFieldValidator>
如果你想需要的領域。
來源
2012-09-27 06:13:59
Dai
那麼你的正則表達式當然可以簡化,但它確實匹配「08:30 AM」 - 所以目前還不清楚問題出在哪裏。 –