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.
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.
(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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With