Clientside validation attributes on hidden,radio, dropdown elements by default in asp.net mvc 3

1.4k Views Asked by At

I'm using ASP.NET MVC 3 + FLUENT VALIDATION + NINJECT

I have model X and rules for that model are something like this:

RuleFor(c => c.FirstName).NotEmpty();
RuleFor(c => c.LastName).NotEmpty();

I spotted a little strange thing, the engine puts validation attributes on all hidden elements and on dropdowns, radio buttons, etc.., and I didn't specified this in the validation configuration for that model, so I guess it is by default...

<input type="hidden" value="1" name="Id" id="Id" data-val-required="&amp;#39;Id&amp;#39; must not be empty." data-val-number="The field Id must be a number." data-val="true">

Validation works because hidden element always have a value, but I have a problem with radio buttons. For example, if I don't want one radio button always to be selected by default but empty and if I want to put validation rules on that item, the rendering puts default validation attributes and on top of my rules, so it's getting messed up and validation doesn't work properly...

Anyone had similar issues or knows about this, or do I have to pull the ASP.NET MVC source and look it up by myself? :)

Semi-Lazy and little-pushed-down-by-deadlines coder

Edit:

I tried proposed solution from this link:

Fluent Validations. Error: Validation type names in unobtrusive client validation rules must be unique

but asp.net mvc emits required attributes on each field regardless of AddImplicitRequiredAttribute settings...

1

There are 1 best solutions below

9
On

Make the Id property on your view model a nullable integer.

So instead of:

public int Id { get; set; }

you should use:

public int? Id { get; set; }

Same stands true for any other value types that you don't want to be required. You should use nullable types.

Html helpers automatically emit data-val attributes for all non-nullable types which is by design and if you do not want this behavior you will have to write your own custom HTML helpers to generate your input fields and dropdowns. You can no longer rely on TextBoxFor and DropDownListFor helpers as that's how they are designed.