How to customize validation error message given by text-danger?

橙三吉。 提交于 2020-01-23 07:34:03

问题


I have a dropdown list on one of my pages in my MVC .NET Core project that I want to customise the default validation text for.

<select asp-for="ProductID" class="form-control" asp-items="ViewBag.ProductID">
    <option value="">--Select Product --</option>
</select>
<span asp-validation-for="ProductID" class="text-danger" />

The standard validation error message given is "The Product ID field is required". I want to change this to something else.

I have tried using this

 <span asp-validation-for="ProductID" class="text-danger">Please enter a product</span>

But the error message displays when the page loads instead of when the button is clicked

What is the appropriate way to customise validation text?


回答1:


That's normally done in the ViewModel you want to return to the Controller:

public class SomeViewModel
{
    [Required(ErrorMessage = "Your elegant error message goes here")]
    public int ProductId { get; set; }
}



回答2:


If you do not require ViewModel then you can use the following,

Add "data-val-required" for message

Then "data-valmsg-replace" will display the same



来源:https://stackoverflow.com/questions/50435891/how-to-customize-validation-error-message-given-by-text-danger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!