.netasp.net-mvcvalidationenterprise-libraryvalidation-application-bl

Integrate ASP.NET MVC validation with Enterprise Library validation


I am already using Enterprise Library 5 Validation for my model (which is used also in WCF methods), so I decided that I would like to avoid redundant validators from ASP.NET 4 MVC with DataAnnotations.

But it seems, Enterprise Library Validators are not picked up automatically by MVC.

if I use MVC DataAnnotations:

[RegularExpression(MyValidationExpressions.Email, ErrorMessage = MyValidationMessages.InvalidEmailMessage)]
public virtual string Email { get; set; }

HTML contains data-val-regex-pattern and the field is being validated client-side.

But if I use the existing EL based validation:

 [RegexValidator(MyValidationExpressions.Email, MessageTemplate = MyValidationMessages.EmptyFieldMessage))]
 public virtual string Email { get; set; }

it does not display validation errors client-side, and the generated HTML does not have any validation attributes.

What am I missing here, how do I force MVC to use the existing EL validators both client-side and server-side?

Solution:

I accepted the solution to move completely to DataAnnotations. It is the easiest way and it works fine with both EntLib 5 and MVC 4. But there is a little catch with ValidationFactory - I had to replace CreateValidatorFromAttributes with CreateValidator and specific flags. See this article for explanation about how DataAnnotations work with ValidationFactory:

CreateValidatorFromAttributes doesn't use DataAnnotations Attributes

Also DataAnnotations have the [Required] attribute which deals nicely with empty strings and strings which contain only spaces. There were some problems on VAB with that.


Solution

  • The reason why this doesn't work is because VAB's RegexValidatorAttribute does not inherit from System.ComponentModel.DataAnnotations.RegularExpressionAttribute, but directly from ValidationAttribute. Because of this MVC doesn't know how to handle it.

    There is a way to change the way MVC does this handling, but I don't know how. But why don't you just replace the usage of the RegexValidatorAttribute with DataAnnotations' RegularExpressionAttribute? Validation Application Block 5 is able to handle DataAnnotations` attributes, so if the DataAnnotations attributes are working, just use them.