Data Annotation Ranges of UK Datetime fields

久未见 提交于 2019-12-23 18:21:13

问题


I want to use Data Annotations to validate DateTime fields, but I'm running into problems. According to documentation on MSDN (http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.rangeattribute.aspx), the following should do the job

[Range(typeof(DateTime), "1/2/2004", "3/4/2004",
    ErrorMessage = "Value for {0} must be between {1} and {2}")]

However, this marks any date I enter as invalid!

At first I thought it was not picking up UK dates (when I tried 26/2/2004) but I can't even get it to use dates such as 2/2/2004.

I'm using the dataannotations within MVC2, and using the MicrosoftAjax framework for clientside validation.

Any suggestions?

Thanks


回答1:


Well, a few years have gone past and I revisited this same issue with MVC4 and I can tell you that it has apparently been resolved.

I created a very simple default MVC4 site, and gave a date member the following attributes

    [Required]
    [DataType(DataType.Date)]
    [Range(typeof(DateTime), "1/2/2004", "3/4/2004", ErrorMessage = "Value for {0} must be between {1} and {2}")]
    public DateTime BlogDate { get; set; }

The validation now works perfectly under UK data system, disallowing a date 2/1/2004, allowing a date of 4/3/2004 or 26/3/2004.

The template I was using took advantage of code-first EF4, but I don't have any reason to suspect that it hasn't been fixed generally, since the javascript is working properly too.

So if you are using MVC2 this may still be a problem, but the best solution which I've found is to use MVC4 as long as it is available to you.




回答2:


As far as i know the RangeAttribute can only validate number on client side, you'll have to write a custom javascript validator for this to work...

check out http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx for an example on how to do this.



来源:https://stackoverflow.com/questions/2251834/data-annotation-ranges-of-uk-datetime-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!