Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 667
crazyPen Avatar asked May 20 '18 14:05

crazyPen


People also ask

How do you show custom validator error message in validation summary?

In order for the Validator 's error message to display in the ValidationSummary , you need to set the Validator s Display="none" . I also set Text="" . C.C. C.C.

How do I create a custom error message in ValidationSummary?

To display a custom error message, first of all, you need to add custom errors into ModelState in the appropriate action method. As you can see in the above code, we have added a custom error message using the ModelState. AddModelError() method.


2 Answers

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; }
}
like image 145
Camilo Terevinto Avatar answered Oct 18 '22 18:10

Camilo Terevinto


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

like image 35
BV Winoya Avatar answered Oct 18 '22 16:10

BV Winoya