aspnetcore
aspnetcore copied to clipboard
[Blazor] InputBase - failed parsing (eg. InputNumber) triggers field validation
Is there an existing issue for this?
- [x] I have searched the existing issues
Describe the bug
If the parsing of input value fails (TryParseValueFromString() returns false), InputBase triggers EditContext.NotifyFieldChanged(FieldIdentifier); which causes all the other field validations to run although the Value of the field did not change (CurrentValue remains unchanged, ValueChanged is not invoked, Model is not changed).
https://github.com/dotnet/aspnetcore/blob/049814ca468cad1ea1e29412e0aa3eea182a63c1/src/Components/Web/src/Forms/InputBase.cs#L142-L143
Expected Behavior
EditContext.NotifyFieldChanged() should be called only when the Value of the field changes (causing revalidation of the field).
Steps To Reproduce
Simple repro:
<EditForm Model="formModel">
<DataAnnotationsValidator />
<InputNumber @bind-Value="formModel.Value" />
<button type="submit">Submit</button>
<ValidationSummary />
</EditForm>
@code {
private FormModel formModel = new FormModel();
public class FormModel
{
[Required]
public int? Value { get; set; }
}
}
- Focus on the empty
inputand type1e+10as an unparseable input. Hit Tab to triggeronchangefor theinput. - The
ValidationSummarydisplays both theParsingErrorMessageand the regular validation message from theRequiredAttribute(sinceformModel.Valueremainsnullwhen the input can't be parsed):
BTW: In contrast, if you reset the page:
- Enter any valid number into the
input, e.g.,5. Triggeronchangeby leaving theinput. - Focus on the
inputagain, replace the5with1e+10, and leave theinput. - The
ValidationSummaryonly displays theParsingErrorMessage, as model validation is satisfied (formModel.Valueis still5).
https://github.com/dotnet/aspnetcore/blob/049814ca468cad1ea1e29412e0aa3eea182a63c1/src/Components/Web/src/Forms/InputBase.cs#L142-L143
I think EditContext.NotifyFieldChanged() should not be called when the field's value hasn't changed (which is the case if parsing fails). I'm not sure why the EditContext.NotifyFieldChanged() call is there (possibly from the initial implementation of input components by @SteveSandersonMS), but if the intent was to ensure ParsingErrorMessage gets displayed, it should be managed by the subsequent EditContext?.NotifyValidationStateChanged(); call.
Exceptions (if any)
No response
.NET Version
9.0.100-rc.1.24452.12 (same on any earlier)
Anything else?
If we agree this needs to be changed, I can prepare a PR to fix it (including new E2E tests).