2
votes

I'm using client-side, unobtrusive validation in MVC 3. I have a field called MinPrice only decorated with DisplayName and Range attributes. But it is failing client-side validation saying "The MinPrice field is required". I have no idea why and I definitely don't have a required attribute anywhere applied to it.

    [DisplayName("Asking Price")]
    [Range(0, 99999999, ErrorMessage="Invalid number")]
    public int MinPrice { get; set; }

What's causing it?

(Note: I can see the data-val-required="The Minprice field is required" attribute rendered in the html source, so something to do with the new unobtrusive routines is putting it there). I don't seem to have this problem with other fields..

2

2 Answers

12
votes

FYI, This has nothing to do with Linq to SQL really.

An implicit [Required] attribute is applied to MinPrice as it is an int which is, by definition, not-nullable (as opposed to int? which is nullable).

This behaviour is implemented by

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes

which defaults to true.

You can disable this behaviour by setting it to false in your Global.asax

0
votes

Ok call me an idiot.

But I just discovered that it IS DEFINITELY getting the "NOT NULL" status from LINQ to SQL and that is forcing it to become a required field, even though I haven't decorated it what that myself. So my own fault, because I had made this a mandatory field in SQL.

But it seems stupid that it listens to that, yet it doesn't automatically bring across other validation attributes such as varchar(100) becoming a StringLength(100) for example.

Anyway, solved my own problem! Cheers.