开发者

ASP.Net MVC 2.0 Date validation not working

开发者 https://www.devze.com 2023-02-01 07:25 出处:网络
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.

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 };
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号