views:

95

answers:

1

I want to write a custom ValidationAttribute that checks if the given value is unique or not.

The problem is that in the edit screen, it is not guaranteed that the user actually changed the value, resulting in a false error.

Is there a way to check in my attribute whether the value actually changed? Or can I trigger the attribute only when the value has changed?

I'm getting the feeling this requirement maybe just doesn't belong in an attribute?

+1  A: 

When you say ValidationAttibute, do you mean using DataAnnotations? If so, then all of this applies, else, sorry, I misunderstood and only part of this will.

I think your best bet is to do this in the repository or BLL using your unique key for the record, at least this is how I did it. Get the previous values of the record and see if they changed. If they did change, then run your uniqueness checks.

If you can get this logic into the ValidationAttribute, then more power to you, but I am not sure if a validationAttribute would be the best thing since there are ways to get around them. From my understanding of these attributes, you should use them as supplements only to business logic validations and not as the only way that you validate your model.

See here for more info on DataAnnotations

EDIT: Fair enough, now let's see if I can give an answer to help you :) Check out this link, it is the code for uniqueness checking on any property in any table. Pretty in-depth LINQ to SQL stuff, but looks like it works well. You should be able to decorate any property with this just like using the <Required> or <StringLenght> attributes.

ASP.NET Forums

Tommy
The unique check is also enforced on the model, but I wanted to make an attribute (or data annotation) out of it so I could leverage the automatic client side checking and have my business requirement rules at one spot.
borisCallens