Sorry for the necromancer answer, but I recently bumped into this, and I have found a simpler solution. ModelStateDictionary
supports this feature natively. Simply use ModelState
instead of Validation
and you no longer need the custom validator, the initializer method, or any other artifacts; everything is baked right in:
Trigger validation on a specific form element
if (!usernameIsValid)
{
ModelState.AddError("username", "That username is already taken.");
}
ModelState also lets you add form-wide validation error messages, just like Validation:
Trigger validation on the whole form
if (password != confirmation)
{
ModelState.AddFormError("Password and confirmation password do not match.");
}
Another advantage of this approach is that ModelState
works in both ASP.NET Web Pages and ASP.NET MVC. On the other hand, Validation
is proprietary to ASP.NET Web Pages, which might complicate things if you ever wish to migrate your project to MVC.
Resources