I was just wondering why the Range validation attribute can take a Type and two strings as parameters? Is this for validating strings against an Enum or something like this?
Also what I am trying to do is find an easy way to validate a 3 character string which must be present in an enum, any sugestions?
Thanks, Alex.
I did find the Range ctor you mentioned fishy. Couldn't help but investigate. (So I wrote this answer like a log while investigating.)
From MSDN
public RangeAttribute(
Type type,
string minimum,
string maximum
)
Note : MSDN says the Type
should be IComparable
. And, their example description says its for a date comparison when its not!.
So since I had my production asp.net mvc3 app opened I tried this on a with a date time like this:
[Range(typeof(DateTime),"1-Jan-1910","1-Jan-2060")]
When I run it this happens:
Note how although I specified the minimum and maximum with dashed and no time, it gives a different format, so its probably TryParsing
the strings right? But I'm sure it can't possibly ICompare
the two on the client side!? Now no matter what date I enter still shows the error. (The Date is entered as 11-Mar-20 (20 as in 2020).)
I tried char (below), since thats an IComparable
too. Same thing. It can't actually manage to do a range comparison on the client side.
[Range(typeof(char), "a", "g")]
Just remove Client Validation! I Removed References to JQuery validation and Unobtrusive validation and viola! It works perfect. It posts, then shows the errors correctly when the values (Both Char and Date) are NOT within the specified range.
Note: Maybe someone can expand this solution to disabling ONLY certain fields for client validation.
Hope this was helpful.
I've also noticed that jQuery Validation does not play well with the ASP MVC Range-validator (it seems like jQuery Validation plugin requires the range values to be numbers).
A simple solution is to turn off validation for the specific fields. The server side validaton will work anyway.
The following example will remove the "range" rule from all input fields with a "date" class:
$('input.date').each(function() {
$(this).rules('remove', 'range');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With