I have a simple Blazor search form with multiple search parameter fields. Each field has its validation message defined in a class, but I'd like to be able to pass extra text into one of the field's validation messages, as that specific field's name is actually variable based on a value pulled from a database. So I can't just say "First Name is required", because sometimes the field's label doesn't say "First Name", but instead says "Client Name" or "Vehicle Make and Model", and I want the validation message to reflect the current field name.
So, is there a way to pass in dynamic text to the ValidationMesage?
sample code:
<div class="row">
<label class="col-12 col-sm-4 col-form-label">@FirstFieldLabel:</label>
<div class="col-12 col-sm-8 ps-2">
<InputText id="FirstField "
class="form-control form-control-sm"
@bind-Value="@SearchFields.FirstField " />
<ValidationMessage For="() => SearchFields.FirstField " />
</div>
</div>
@code {
private string? FirstFieldLabel { get; set; }
private class SearchFields() {
[StringLength(100, ErrorMessage = "Must be between 3 and 100 characters.")]
public string? FirstField { get; set; }
}
protected override async Task OnInitializedAsync() {
FirstFieldLabel = _dbLayer.GetFirstFieldLabel();
}
}
I'd like to insert FirstFieldLabel into the SearchFields() ErrorMessage for FirstField, so that the message instead reads "FirstField must be between 3 and 100 characters.".
EditFormand did you includeDataAnnotationsValidator?