views:

35

answers:

1

Is there away to add and remove DataAnnotations, in particular the [requried], from the code side of things? My problem is that I want to give the user the ability to save an incomplete form in our crud applications but at the same time use the power of the DataAnnotations validation.

If this is not possible, what is the best way I can go about this?

A: 

You can keep the DataAnnotation attributes on your model and then just manually clear the validation errors as needed from code. It might look something like this:

if (certainCondition == true) {
   ModelState["someKey"].Errors.Clear();
   ModelState["anotherKey"].Errors.Clear();
}
Larsenal
Here you are not removing the DataAnnotation but just clearing the ModelErrors. The problem with this is that it removes all the errors and not a particular one. For example, say "someKey" is both required and has a length restriction. By running clear, you lose both of these. If you that length restriction is there because your db has restriction on the field length, then you will lose data on save if you attempt to save. This would work however, if you could remove just select errors.
Scott
Although I haven't done it personally, I believe you can remove individual errors for any key. In your example, why not just have a StringLength attribute? If you want users to be able to save an "incomplete" form, then in what sense are fields "Required"? Is it really just a business rule that says input is not "complete" unless certain fields are filled in?
Larsenal