I am new to asp.net core. I have a form which is generated dynamically. I want the validation error message to be "The value must be numeric" instead I get
C#
"The value 'a' is invalid."Here is my View Model:
C#
[RegularExpression("^[0-9]*$", ErrorMessage = "The value must be numeric")]
public List Units_Service { get; set; }Here is my form code:
C#
for (int i = 0; i
@Html.DisplayFor(model => model.Workload_Category_Name[i])
@Html.TextBoxFor(model => model.Units_Service[i], new { style = "width: 15%", MaskedTextBox = "9999" })
@Html.ValidationMessageFor(model => model.Units_Service[i])
}Despite the fact, I have put the custom error message in my View Model as shown above, I keep getting the default message "The value '' is invalid". Please what is the solution to this kind of scenario ?

Mahesh ChandRank #1 · 393.3K reputationPosted Nov 1, 2023, 11:09 AM EDT
You need to customize the error message somewhere. Something like this I got from ChatGPT :)
In the Model:
You can use data annotations to customize the error messages on properties.
public class YourModel { [Required(ErrorMessage = "Please enter a value")] public string YourProperty { get; set; } }In the Controller:
You can customize the error response based on the model state.
[HttpPost] public ActionResult YourAction(YourModel model) { if (!ModelState.IsValid) { // Adding a custom error message ModelState.AddModelError("", "Custom error message here"); return View(model); } // Your code here if the model is valid return RedirectToAction("SuccessAction"); }In the View:
Display the error message using the validation summary or display it next to the field.
@using (Html.BeginForm()) { @Html.ValidationSummary(true, "", new { @class = "text-danger" }) }