简体   繁体   中英

ASP.Net MVC 2.0 Date validation not working

I am trying to validate date value in dd/mm/yyyy format.I am getting error message even if I enter the date in correct format.

Here is my Code :

[Required(ErrorMessage = "Required Field.")]            
[RegularExpression(@"^((0[1-9])|([1-2][0-9])|3[0-1])\/((0[1-9])|(1[0-2]))\/[0-9]{4}$",ErrorMessage="Please enter in dd/mm/yyyy")]
[DataType(DataType.Date,ErrorMessage="Please enter date.")]
public DateTime BeginningDate { get; set; }

The error message you get comes from model binder, it has nothing in common with your attributes. I think, that if you want to check regular expression, you should use:

public string BeginningDate { get; set;}

and then convert it to DateTime by yourself, after model binding. You know that date has to be provided in specific format, but model binder is not that smart, uses web.config/server setting, and throws an error. Checking DateTime type by regular expression doesn't make sense, because it is already DateTime, not string. Model binding comes first and then validation.

public class DateRegexAttribute : RegularExpressionAttribute, IClientValidatable
    {
    public DateRegexAttribute(string pattern)
        : base(pattern)
    {
    }

    public override bool IsValid(object value)
    {
        DateTime date;
        try
        {
            date = (DateTime) value;
        }
        catch
        {
            return false;
        }

        var input = date.Date.ToShortDateString();

        Match match = Regex.Match(input, Pattern, RegexOptions.IgnoreCase);

        return match.Success;
    }


    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRegexRule(ErrorMessageString, Pattern);
        return new[] { rule };
    }
}

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