3

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

Faris Zacina
  • 14,056
  • 7
  • 62
  • 75
user3428422
  • 4,300
  • 12
  • 55
  • 119

1 Answers1

1

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; }
}
Faris Zacina
  • 14,056
  • 7
  • 62
  • 75
  • Thanks, way ahead of ya! I am doing my own RequiredOn Attribute, but having trouble with the value parameter in the override isValid method being null! so learning now :) – user3428422 Oct 15 '14 at 09:15
  • Great!.. i am glad you figured it out ;) – Faris Zacina Oct 15 '14 at 09:16
  • Thanks, but how do you pass in a property into the attribute? like `public int Status_ID{get; set:}` `[RequiredOn(ID = Status_ID, ErrorMessage = "The Name field is required")] ` I dont want to hardcode a ID. – user3428422 Oct 15 '14 at 09:32
  • Check out this link: http://stackoverflow.com/questions/4518291/how-to-pass-compiler-checked-property-names-expression-tree-to-a-custom-attrib – Faris Zacina Oct 15 '14 at 09:44
  • Ok the above can be done by going too http://stackoverflow.com/questions/3713281/attribute-dependent-on-another-field How I done what I wanted, if anyone else wants to know if using the same logic, give us a comment and I will help :) – user3428422 Oct 15 '14 at 11:30