Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data-Annotations - EntityValidation removal 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, is it only required on different conditions.

So I remove the ModelState Key when the correct condition is met

if (Status_ID != 2 && Status_ID != 3)
{
    ModelState.Remove("Name");
}

Which works, but when EF tries to save the entity, I get a EntityVaildationError because I am guessing I have the Data Annotation"Required" on the property which can never been taken off programmatically regardless of the ModelState

How else could I achieve what I want?

Cheers

like image 792
user3428422 Avatar asked Jul 10 '26 14:07

user3428422


1 Answers

That is not possible with the existing RequiredAttribute.

However, you can implement your own custom conditional validation attribute.

Here are some links to guide 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 custom RequiredIf conditional validation attribute you can set the condition like:

public class ValidationSample
{
   [RequiredIf("PropertyValidationDependsOn", true)]
   public string PropertyToValidate { get; set; }

   public bool PropertyValidationDependsOn { get; set; }
}
like image 66
Faris Zacina Avatar answered Jul 12 '26 04:07

Faris Zacina