简体   繁体   中英

Custom Date validation Format

Using C#

C# Code

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
    if(e.Value.Length == 8)
        e.IsValid = true;
    else
        e.IsValid = false;
}

Page code

<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtoedate" onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly 8 characters long!" />

The above code is working for the length, but i want to check the date format like this "yyyy-mm-dd", for checking this date format, how to change my code.

Need Code Help

Well, firstly, your date format isn't 8 characters long, so you'll need to fix that to 10. Then your best bet is a DateTime.TryParseExact with the specific format you want to validate.

DateTime value;
e.IsValid = DateTime.TryParseExact(e.Value, "yyyy-MM-dd",
    CultureInfo.InvariantCulture, DateTimeStyles.None, out value);

You can get away with InvariantCulture because you are only dealing with the numeric representations of the date parts and are specifying the format exactly.

尝试日期的正则表达式

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM