Reputation: 602
I am building a search form which needs multiple fields. A radio button indicates which fields are required for input like so :
[ ] Field 1
[.] Field 2
Field 3
[ ] Field 4
In the above case, Field 2
and Field 3
are now required since the associated radio button is checked. To accomplish this, I have implemented the RequiredIf
validation attribute, and it works properly.
My problem are the other validations. In this case, Field 1
also has a minimum length validation. If Field 1
has any value that does not respect the minimum length validation, the form is now invalid and cannot be submitted.
I need a way to disable validation on the fields that are not required. (And also be able to set them back as another radio button is checked).
The fields cannot be set to "disabled=disabled" which solves the issue because of client requirements.
I have tried removing the data-val
attributes or setting them to false
on the said fields, then parsing my form again, failing miserably.
Edit: Just making sure. The problem is client-side validations.
Upvotes: 1
Views: 669
Reputation: 6528
Remember that there are 2 validations happening: client and server side. Hence, removing the data-val attribute will not help.
Now, in your models I reckon you are using [attributes] to add these validation rules. I don't think this method will not let you do conditional validations.
In this case FluentValidation can help you. http://fluentvalidation.codeplex.com/
It is quite simple to do, and you should be able to do something like:
RuleFor(model => model.Field).NotEmpty().When(model => model.FieldEnabled);
Upvotes: 1
Reputation: 602
Setting the fields as "disabled" works as intended. The client has changed his mind about this requirement. Sometimes it is the best solution.
This is still open for better solutions.
Edit :
I had not thought about searching for doc on the validation plugin. There seems to be some pretty interesting methods available to use like rules ( "remove", rules ).
Upvotes: 0