Data-Annotations - deleting EntityValidation based on condition in code
I have a column that is required in my model
[Required(ErrorMessage = "The Name field is required")]
public string Name{ get; set; }
However, this is only required under different conditions.
Therefore, I remove the key ModelState
when performing the correct condition
if (Status_ID != 2 && Status_ID != 3)
{
ModelState.Remove("Name");
}
Which works, but when EF tries to save the object, I get EntityVaildationError
because I assume I have a Data Annotation
"Required" for a property that can never be cleared programmatically no matterModelState
How else can I achieve what I want?
Greetings
source to share
This is not possible with the existing one RequiredAttribute
.
However, you can implement your own conditional validation attribute.
Here are some links to get you in the right direction:
http://blogs.msdn.com/b/simonince/archive/2010/06/04/conditional-validation-in-mvc.aspx http://blogs.msdn.com/b/simonince/archive/2011/02 /04/conditional-validation-in-asp-net-mvc-3.aspx http://blogs.msdn.com/b/simonince/archive/2011/09/29/mvc-validationtookit-alpha-release-conditional- validation-with-mvc-3.aspx
Once you implement your own conditional validation attribute RequiredIf
, you can set the condition like this:
public class ValidationSample
{
[RequiredIf("PropertyValidationDependsOn", true)]
public string PropertyToValidate { get; set; }
public bool PropertyValidationDependsOn { get; set; }
}
source to share