2012-09-27 55 views
1

我正在使用asp.net使用vb代碼處理web應用程序。使用正則表達式對時間HH:MM am或pm格式進行驗證

我有一個我正在使用正則表達式驗證器的時間字段的文本框。

我想要的格式是HH:MM am。正在使用的正則表達式是"(0[1-9]|[1][0-2])[:]" + "(0[0-9]|[1-5][0-9])[ ][A|a|P|p][M|m]"

我正在輸入時間示例:08:30 AM或08:30 PM,但正則表達式顯示錯誤消息。

任何人都可以用正確的正則表達式來幫助我。

所有三江源提前

舒卜哈

+0

那麼你的正則表達式當然可以簡化,但它確實匹配「08:30 AM」 - 所以目前還不清楚問題出在哪裏。 –

回答

7

使用的RegularExpressionValidator及以下ValidationExpression。我已經用過了。

ValidationExpression="^(1[0-2]|0[1-9]):[0-5][0-9]\040(AM|am|PM|pm)$" 
0

你不需要使用正則表達式,使用DateTime.TryParseDateTime.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>如果你想需要的領域。

相關問題