Ask Your Question
2

How can I make the "Custom ErrorMessage" feature of ASP.NET Core Model Data Annotations visible?

asked 2022-01-04 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-08-05 04:00:00 +0000

qstack gravatar image

To make the "Custom ErrorMessage" feature of ASP.NET Core Model Data Annotations visible, you can follow these steps:

  1. Define the ErrorMessage in the Data Annotation attribute like so:
[Required(ErrorMessage = "Please enter a valid email address")]
[EmailAddress(ErrorMessage = "Please enter a valid email address")]
public string Email { get; set; }
  1. In your view, use the ValidationSummary helper to display all validation errors for the model:
@model MyViewModel

@using (Html.BeginForm())
{
    @Html.ValidationSummary()

    <div class="form-group">
        @Html.LabelFor(model => model.Email)
        @Html.TextBoxFor(model => model.Email, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Email)
    </div>

    <button type="submit" class="btn btn-primary">Submit</button>
}
  1. Include the jquery.validate and jquery.validate.unobtrusive libraries in your view:
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js"></script>

This will enable client-side validation for your model and display the custom error message if the validation fails.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-01-04 11:00:00 +0000

Seen: 8 times

Last updated: Aug 05 '22