Search code examples
asp.net-mvcblazorblazor-client-sideasp.net-blazor

Display html or multiline message in ValidationMessage in Blazor?


Problem

Display list of error messages for password as below:

  1. Must contain at least one upper case letter.
  2. Must contain at least one lower case letter.
  3. Must contain at least one number.
  4. Must contain at least one symbol.
  5. Must be 6 character long.

In MVC

We can achieve this by below code:

@Html.Raw(HttpUtility.HtmlDecode(Html.ValidationMessageFor(m => m.Email).ToHtmlString()))

How can we do the same thing in Blazor? Please let me know if more things is required to support the question.


Solution

  • I also need to do this to have a custom validation but that looks like ValidationMessage and as you said in the comments

    How to use the same with the validation message in the Blazor. FYI - validation message in Blazor looks as signUpModel.Email)">

    The way to do this is just do the same as ValidationMessage does and change how it renders

    You can just copy the code from the repo and do some changes.

    • First, it would be good if you change the name of the class for something like CustomValidationMessage or anything you want.
    • You will see the method BuildRenderTree which is build the html with the validation messages.
    • If you know how to use BuildRenderTree you can just edit that but I recommend you to remove that method and create a .razor file that will render the messages.
    • Do the same logic as in that method (foreach the messages) and inside you can render whatever you want (e.g. use MarkupString(message)) .

    .razor

    foreach (var message in CurrentEditContext.GetValidationMessages(_fieldIdentifier))
    {
        @* use message the way you want*@
    }