6

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?

M.Azad
  • 3,673
  • 8
  • 47
  • 77
  • If it is not required in some cases, why do you set an attribute? Attributes are static, why not create a property or something like that? – H.B. Feb 21 '12 at 15:38
  • 1
    In your code it might be called *departmant*, but your error message should definitely call it *department*. – spender Feb 21 '12 at 15:44
  • @ H.B. In fact my business changed in one case ....In another case this property is required... – M.Azad Feb 21 '12 at 15:44

4 Answers4

2

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.

Community
  • 1
  • 1
Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208
1

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

user338146
  • 11
  • 2
0

I've got round this issue in the model, in some cases it's not ideal but it's the cheapest and quickest way.

public string NonMandatoryDepartmentCode
{
    get
    {
        return DepartmentCode;
    }
    set
    {
        DepartmentCode = value;
    }
}

I used this approach for MVC when a base model I inherited contained attributes I wanted to override.

Phil Cooper
  • 3,083
  • 39
  • 63
0

I would remove the RequiredAttribute from your model and check it once you've hit your controller and check it against whatever causes it to not be required.

If it falls into a case where it is required and the value is not filled in, add the error to the ModelState manually

ModelState.AddModelError("DepartmantCode", "DepartmantCode is Required");

You would just lose the validation on the client side this way

Anthony Shaw
  • 8,146
  • 4
  • 44
  • 62