Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate some fields some of the time?

I'm using C# in .Net-Core MVC and I have a form that users will need to fill out.

All of the fields that are shown on the page are required to be filled out. The issue I'm running into is that some of the fields on the form are hidden and others are displayed based on choices previously made on the form.

If I put the [Required] tag on all of the fields in the model, when I validate the ModelState, it flags the not displayed fields as invalid.

Is there a way that when I try to validate the ModelState, I can validate only the fields displayed on the page and ignore the fields that have been hidden?

Thanks.

like image 642
Shaun.S Avatar asked Dec 11 '25 21:12

Shaun.S


1 Answers

Unfortunately the [Required] works globally in MVC.

You will need to develop your own validation attributes. Hopefully someone already did it but for MVC with .NET Framework (see the code here):

For validations that has the form of: “Validate this field only when this other field has certain value”, I have coded 3 attributes: RequiredIf, RangeIf and RegularExpressionIf that inherints from ValidationAttribute.

Now you will need to translate it in order to work for .NET Core.

If you are looking for a more generic solution, the Web Forms framework has a very good concept of Validation group. It allows you to validate - or not - logically grouped properties.

like image 185
Guillaume S. Avatar answered Dec 14 '25 10:12

Guillaume S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!