In ASP.Net MVC 5
View
we have an automatic error message popped-up when a control/input in the View
tries to create column value in the database (or a field value in a class
) which is supposed to be unique but we violate it - such as when creating new user account's email with an already existing email as shown below.
Now, I am supposed to change the error message above into a local language in my project:
... is already taken <-> ... [is already taken in local language]
How to change the "[field value] already taken" (automatic) error message?
According to this post:
Issue with username validation message in asp.net identity
We could just try to search for "Name {0} is already taken" in the whole solution, but when I did that, I couldn't find it.
Was that a valid solution in earlier MVC
but outdated for MVC 5
?
(Note: unfortunately, the post does not indicate which ASP.Net MVC version the OP is working with)
I have implemented this via using Remote in System.ComponentModel.DataAnnotations
. Please refer following code :
In ViewModel
(Properties
) :
[Display(Name = "Email")]
[Remote("IsValidUserName", "Remote", AdditionalFields = "Email", HttpMethod = "Post")]
public string Email { get; set; }
Here "Remote" is a Controller
Name and "IsValidUserName" our Method
. Like below:
public class RemoteController : Controller
{
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult IsValidUserName()
{
string email= Request.Form["Email"];
string message = "Email '"+ email+ "' is already taken";
if (!string.IsNullOrEmpty(email))
{
using (DbContext db = new DbContext())
{
if (!db.tb_Users.Any(x => x.email== email))
{
message = string.Empty;
}
}
}
if (message == string.Empty)
return Json(true, JsonRequestBehavior.AllowGet);
else
return Json(message, JsonRequestBehavior.AllowGet);
}
}
and on View
page you have to use this like below:
@Html.TextBoxFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
Output will be :
Points to remember:
You have to use following JavaScripts
for running this:
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.jss"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
Hope it helps you.
Thanks.
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