I am using from attribute validation in my project.
[Required(ErrorMessage = "DepartmentCode is Required")]
public string DepartmentCode { get; set; }
In some case DepartmentCode isn't required. How can I dynamically ignore Validation in my case?
It is not possible to add Attributes in run-time. Attributes are static and cannot be added or removed.
We can use the RemoveAt method to remove an item at the specified position within a List. The Remove method removes the first occurrence of a specific object from a List. The Remove method takes an item as its parameter. We can use the RemoveAt method to remove an item at the specified position within a List.
In C#, attributes are classes that inherit from the Attribute base class. Any class that inherits from Attribute can be used as a sort of "tag" on other pieces of code. For instance, there is an attribute called ObsoleteAttribute . This is used to signal that code is obsolete and shouldn't be used anymore.
Take a look at: Remove C# attribute of a property dynamically
Anyway I think the proper solution is to inherit an attribute from RequiredAttribute
and override the Validate()
method (so you can check when that field is required or not). You may check CompareAttribute
implementation if you want to keep client side validation working.
Instead of dynamically adding and removing validation, you would be better served to create an attribute that better serves this purpose.
The following article demonstrates this (MVC3 with client-side validation too): http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx
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