1

I created a custom validation message component in Blazor like this:

<div class="text-danger">
   <ValidationMessage For="@(()=>model)"/>
</div>

@code {
    [Parameter]
    public object model { get; set; }
}

and I have a class:

public class LoginViewModel
{
    [Required(ErrorMessage = "please enter {0}")]
    public string PhoneNumber { get; set; }
}

then I use this component in a razor page:

<CustomClientValidation model=@(LoginModel.PhoneNumber)/>

and with an object defined in the code section of the page:

LoginViewModel LoginModel;

but after running the application, even though the PhoneNumber is null, the validation message is not displayed. Where is my mistake?

vmahdavi
  • 399
  • 1
  • 4
  • 9

1 Answers1

0

You can pass the Expression like this:

@using System.Linq.Expressions;
@typeparam TValue

<div class="text-danger">
    <ValidationMessage For=@this.For />
</div>

@code {
    [Parameter, EditorRequired] public Expression<Func<TValue>>? For { get; set; }
}

Or simply inherit directly from ValidationMessage like this:

@inherits ValidationMessage<TValue>
@typeparam TValue

<div class="text-danger">
    @this.BaseContent
</div>

@code {
    // Read only property to get the base component content
    private RenderFragment BaseContent => (builder) => base.BuildRenderTree(builder);
}
MrC aka Shaun Curtis
  • 19,075
  • 3
  • 13
  • 31