Tuesday, May 25, 2010

ValidateIsUnique on Monorail

I have been playing with Castle Monorail quite a bit, and am currently working on building a large administration project using it.  The problem I've run across recently is with validating models when using ARDataBind (or the DataBinder in general).  Even though I was using the recommended code:

if (HasValidationError(model)) {
  Flash["summary"] = GetErrorSummary(model);
  RedirectToReferrer();
  return;
}

But I found that I was still getting an invalid object when the object was being saved, or in other words: the HasValidationError method wasn't catching invalid objects.  I have beating my head against the wall many a time until today when I realized something - the ValidateIsUnique attribute comes from Castle.Activerecord and NOT from Castle.Components.Validator.  Sure enough, I realized that any problems I had with HasValidationError not catching an invalid object came when I used ValidateIsUnique.

So after digging through some code for a couple of hours, I haven't quite found a solution that I like.  I may post on Castle Project mailing list to see if I get some answers there.  As of right now I believe the only way to really validate and catch this attribute if the validation failed is to include a separate catch block after the HasValidationError block:

if (!model.IsValid()) {
  ActiveRecordMediator.Evict(model);
  Flash["message"] = String.Join(",", model.ValidationErrorMessages);
  RedirectToReferrer();
  return;
}

No comments:

Post a Comment