I’ve recently started using Blazor. Is there a way to trigger form model validation only on submit, instead of live on each change?
Just for clarification, let’s say I have something like this:
<EditForm Model="this" OnValidSubmit="SubmitForm">
<DataAnnotationsValidator />
<ValidationSummary />
<Label For="Name">Name</Label>
<InputText id="Name" name="Name" class="form-control" @bind-Value="Name"/>
<button type="submit">Save</button>
</EditForm>
@code {
[StringLength(10, ErrorMessage="Name too long")]
public string Name { get; set; }
private async Task SubmitForm()
{
// ...
// send a POST request
}
}
By default, it seems like the validity of the field and the error messages displayed in the ValidationSummary get re-evaluated on every change of the text input (e.g. as soon as I delete the 11th character from the input, the "too long" message disappears).
I would prefer if the displayed messages would remain frozen until the Submit button is clicked.
I suppose it would be possible to implement it by removing the ValidationSummary component and implementing a custom solution (e.g. displaying a List of error messages that’s refreshed only on submit), but I was wondering if there is some idiomatic solution that I’m not aware of.
2
Answers
When validation occurs is controlled by the Validator you’re using.
There are two events that you can receive from EditContext:
OnValidationRequested
is invoked either whenEditContext.Validate
is called or as part of the form submission process.OnFieldChanged
is invoked every time a field value is changed.A validator uses these events to trigger it’s validation process, and outputs the results to the EditContext’s ValidationMessageStore.
DataAnnotationsValidator
wires up for both events and triggers validation whenever either is invoked.There are other validators out there, and writing your own is not too difficult. Other than those from the usual control suppliers, there’s Blazored, or mine. Mine is documented here – https://shauncurtis.github.io/articles/Blazor-Form-Validation.html. it has a
DoValidationOnFieldChange
setting!@enet’s answer sparked an alternative answer. Build your own DataAnnotationsValidator.
Here’s the EditContext Extensions code. It’s a modified version of the original MS Code with some extra control arguments.
And the
CustomValidation
component:You can use it like this: