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
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; }
}
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