Search code examples
asp.net-coremodel-validationasp.net-validators

How to show asp-for-validation error message in a tooltip instead of span


ASP.NET Core has beautiful way of handle valiadtion. But the validation style showing in frontend is very old school. The way i have followed:

Custom model annotation with error message:

    [Required(ErrorMessage = "UserName is Required")]
    [StringLength(10, ErrorMessage = "Must be between 5 and 10 characters", MinimumLength = 5)]
    [UserNameVal]
    public string UserName { get; set; }

add script for showing message in view

@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

Showing error message with span:

<span asp-validation-for="@Model.UserName" class="text-danger"></span>

And this is resulting a primitive old faishon validation message like the screenshot below

enter image description here

But I want validation style like this with using the default asp-for-validation

enter image description here

Is it possible without writing extra javascript in every page? if possible then how? I have already explored these links: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-3.1 http://jsfiddle.net/2DUX2/ https://www.codeproject.com/Tips/755421/Using-the-jQuery-unobtrusive-validator-with-Twitte


Solution

  • The easiest way to customize validation is to use a third party validation library. Because built in feature is created for general purpose use and it serves most people. The default style can be customized with CSS. When you want custom look and feel, you can't get it through magic. Either you have to write your own CSS style or you have to use another third party library where it was done for you.

    If you check the source view of the default error messages, you will see, the HTML part of that is very simple, and upon that tags you can easily put custom CSS and JavaScript to customize it without touching anything in the C# or razor.

    But sometimes it is time consuming and none wants to write it on their own. So they use third party library to do the job. For example, you can check this link: https://validatejs.org/