How to check or validate the textbox entered date is in DD/MM/YYYY format?
How to check or val开发者_运维问答idate the textbox entered date is in DD/MM/YYYY
format?
Markup:
<asp:Textbox runat="server" ID="TextBox1" />
<asp:CustomValidator runat="server" ControlToValidate="TextBox1" ErrorMessage="Date was in incorrect format" OnServerValidate="CustomValidator1_ServerValidate" />
Code-behind:
protected void CustomValidator1_ServerValidate(object sender, ServerValidateEventArgs e)
{
DateTime d;
e.IsValid = DateTime.TryParseExact(e.Value, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out d);
}
if you want to allow several formats and only them, use next:
DateTime.TryParseExact(e.Value, new[] { "dd/MM/yyyy", "yyyy-MM-dd" }, CultureInfo.InvarinatCulture, DateTimeStyles.None, out d);
Another option is using a regular expression validator. The regular expression below checks for DD/MM/YYYY but of course there is no way to distinguish if something like 01 is DD or MM. Otherwise it does the trick.
<asp:TextBox ID="txtDate" runat="server"/>
<asp:RegularExpressionValidator ID="regexpName" runat="server"
ErrorMessage="This expression does not validate."
ControlToValidate="txtDate"
ValidationExpression="^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$" />
DateTime Result;
DateTimeFormatInfo info = new DateTimeFormatInfo ( );
CultureInfo culture;
culture = CultureInfo.CreateSpecificCulture ( "en-US" );
info.ShortDatePattern = "dd/MM/yyyy";
if ( DateTime.TryParse ( StrDate, info, DateTimeStyles.None, out Result ) )
{
return StrDate;
}
You could use a CustomValidator to check that the entered value is within set parameters.
I.e. 13/12/2001 is valid but 12/13/2001 is invalid.
You will be better off using a calendar control, but if you want to check the date string anyway, use the following code can be used to validate that the is in DD/MM/YYYY format.
DateTime dt;
if (!DateTime.TryParse(texbox.Text, new System.Globalization.CultureInfo("en-GB"), System.Globalization.DateTimeStyles.None, dt))
{
// text is not in the correct format
}
You can use a Custom Validator to check just about anything in text box, but it might be easier to use CompareValidator to check if the text can be converted to a date.
I found an example (in VB but easy enough to read and translate to C#) here: http://quickstarts.asp.net/QuickStartv20/aspnet/doc/validation/default.aspx
However, using some sort of date picker control might be more user friendly.
My approach would be to use a regexvalidator for a first quick test ("does it look like it could be a date") client-side. And then a CustomValidator with a serverside event that tries to perform a DateTime.Parse with my format, to rule out dates like "29 feb 2010".
Personally I don't trust the CompareValidator here, because I don't know for sure what format it uses (but that can be because I didn't investigate enough).
You can't. User some kind of datetime picker instead. Example here.
精彩评论