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.
You can create a ModelValidatorProvider
for Enterprise Library validation. Brad Wilson has a blog post describing how to do this.
However, it looks like this will only perform server side validation. If the attributes you are using are very similar to DataAnnotations, I would recommend using them instead.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.