Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.