Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataAnnotations for valid email address

I am using data annotations for my form where users can register their account. For the email field I have one data annotation for required and one for a valid email. Here you can see that in my viewmodel:

    [Required(ErrorMessage = "The Email field is required.")]
    [EmailAddress(ErrorMessage = "The Email field is not a valid e-mail address.")]
    public string Email { get; set; }

In my view I have the following code:

<form asp-controller="Home" asp-action="RegisterAsync" method="post" class="register-form">
    <br />
    <img src="~/images/logo.png" width="300" />
    <br />
    <br />

    <div class="text-danger">
        @ViewBag.FailedToRegister
    </div>

    <div class="form-group">
        <input asp-for="Name" placeholder=@Localizer["Name"] class="form-control" />
        <span asp-validation-for="Name" class="text-danger"></span>
    </div>

    <div class="form-group">
        <input asp-for="Email" placeholder="Email" class="form-control" />
        <span asp-validation-for="Email" class="text-danger"></span>
    </div>
// Removed code for brevity

Now when I run my app and leave the email field empty I get a nice error message like below.

Correct email error message

But when I fill in something that is not a valid email address then I don't get the same error text like above but I get the following.

Wrong email error message

(Sorry for the dutch message, it means: A valid email address is required.)

But why don't I get the message that I programmed in my ViewModel and how do I fix this?

I also tried to change

[EmailAddress(ErrorMessage = "The Email field is not a valid e-mail address.")]

in my viewmodel to

[DataType(DataType.EmailAddress, ErrorMessage = "The Email field is not a valid e-mail address.")]

, but without luck.

like image 709
Svenmarim Avatar asked Dec 17 '18 12:12

Svenmarim


1 Answers

The unexpected validation you are seeing is coming from your browser. If you add the "novalidate" attribute to your form it will disable it:

e.g.

<form asp-controller="Home" asp-action="RegisterAsync" method="post" class="register-form" novalidate>
like image 101
Rob C Avatar answered Oct 04 '22 08:10

Rob C