3

I am using Entity Framework 4 to provide the model for a ASP.NET MVC3 / Razor2 web application. I am using DataAnnotations to implement validation. I need to limit some dates to the range accepted by the SQL smalldatetime type.

My problem is that I can't get the RangeAttribute to work correctly for a date field. The model metadata definition for the field in question is:

    [Display(ResourceType = typeof(Resources.Patient), Name = "DateOfBirth_Name")]
    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    [DataType(DataType.Date)]
    [Range(typeof(DateTime), "01/01/1900", "06/06/2079", ErrorMessageResourceType = typeof(Resources.Patient), ErrorMessageResourceName = "DateOfBirth_Range")] 
    public System.DateTime DateOfBirth { get; set; }

With this code, whatever value I put into the date field, it is treated as invalid by the application. In case its' relevant, I am using the JQuery-UI date picker with the field in question as well.

Can anyone help please?

1 Answer 1

2

You do not specify where the error occurs, but my guess is that it is client-side(?) jQuery Validation does not work well with the RangeAttribute. To verify, disable jQuery Validation and the valid input should pass the (server) validation.

To get around this you will have to write your own date range validation, e.g. http://blogs.msdn.com/b/stuartleeks/archive/2011/01/25/asp-net-mvc-3-integrating-with-the-jquery-ui-date-picker-and-adding-a-jquery-validate-date-range-validator.aspx

Alternatively you could look into packages such as Data Annotations Extensions or MVC Foolproof Validation to see if they could be used for solving the problem.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Martin4ndersen. Disabling the JS validation libraries for the view enabled correct validation server-side, as you predicted. By itself, the custom attribute showed in the blog gives correct server-side validation, with js enabled. I will take the extra hit to implement the workaround it suggests to get the client-side support working as well. Shame the RangeAttribute and js unobtrusive validation don't work properly together. Would like to see that fixed in a future release of MVC.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.