I have an ASP.NET MVC app that has a form with several fields on it. Three of the fields are grouped together in that only one of them needs to be filled in. The code is currently written making use of the IValidatableObject.Validate
method:
if (String.IsNullOrEmpty(Field1) && String.IsNullOrEmpty(Field2) && String.IsNullOrEmpty(Field3))
{
yield return new ValidationResult("Please fill in one of the fields.",
new [] { "Field1", "Field2", "Field3" });
}
The problem is that it displays "Please fill in one of the fields."
in the validation summary three times, which is not good.
I looked this post and a few other like it that basically recommend creating a custom ValidationAttribute
. I tried doing that but there are two problems with that approach.
The first problem is that if you only apply the ValidationAttribute
to one field as suggested in the link above, it only puts one message in the validation summary, but it also only highlights that one field in red. The other two fields remain normal. If you use an approach where multiple fields have the attribute then you get them all in red but you also get multiple error messages in the validation summary.
The other problem is that when a ValidationAttribute
reports an error, the IValidatableObject.Validate
method no longer runs. So the validation summary only contains the error message related to the ValidationAttribute
even if other issue still exist.
So the basic goals are:
- All three fields need to be highlighted in red when all are blank
- The validation summary should only contain the error message one time
- The
IValidatableObject.Validate
must execute
Any thoughts?