Search code examples
c#asp.net-mvcfluentvalidation

Email check by fluent validation is not the same client as serverside


I'm using FluentValidation to validate my models both client side and server side. I am on the latest version of :

FluentValidation.MVC5

at the time of writing, which is

5.5.0.0

I have the following validator, simplified:

public class MyViewModelValidator : AbstractValidator<MyViewModel>
    {
        public MyViewModelValidator()
        {
                RuleFor(x => x.Email)
                    .EmailAddress().WithLocalizedMessage(() => MyResources.Validation_Email_NotValidAddress)
                    .NotEmpty()
                    .WithLocalizedMessage(() => MyResources.Validation_Email);
        }
    }

Client side it seems to do some basic validation, such as it will not accept anything without text either side of the '@' symbol, however it will accept something like test@test.

The problem arises when I post this data, I have the following in my Controller:

    if (!ModelState.IsValid)
        throw new Exception("Model validation error");

This sees the model as invalid due to the test@test email address and throws an error. So it appears my front end validation is more lax that my server side validation.

Having referred to the documentation, it does state that the Email() method is supported clientside, however there does seem to be some disparity between this server side, and what is being rendered to the front end.

https://fluentvalidation.codeplex.com/wikipage?title=mvc

How can I ensure the client side validation is as thorough as the server side with the email.


Solution

  • As Evgeny touched on above, I eventually opted to use the Matches rule, as this is one of the validators which is supported on the client.

       RuleFor(x => x.Email)
                    .Matches(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$").WithLocalizedMessage(() => MyResources.Validation_Email_NotValidAddress)              
                    .NotEmpty() // <-- and cant be empty
                    .WithLocalizedMessage(() => MyResources.Validation_Email);
    

    The above Regex I believe is used by ASP.NET for the RegularExpressionValidator. And works well for my requirement.