Based on the Blazor University tutorials and many SO/GitHub posts I am trying to create a custom component that inherits from InputBase<int?>.
It displays fine, but on submission the custom validation method TryParseValueFromString() does not fire and so my validation messages are not bubbling up into the edit context, nor displaying:
Setting a breakpoint in the method body further proves the method is never triggering as the breakpoint is never hit.
In time this will have complex validation, so I cannot rely on DataAnnotations validation to provide these checks and want to better understand TryParseValueFromString().
Can somebody please advise how to get the above method to trigger for a non-parseable value?
Page code
@page "/"@using BlazorAppTryParseValueFromString.Component@using static Microsoft.AspNetCore.Components.Web.RenderMode@rendermode InteractiveServer<PageTitle>Index</PageTitle><EditForm Model="myModel" OnValidSubmit="FormSubmit"><ValidationSummary /><p><IntegerComponent @bind-Value=myModel.MyNumber /></p><p><input type="submit" value="Go" /><ValidationMessage For="() => myModel.MyNumber" /></p><p> @Result</p></EditForm>@code { public class MyModel { public int? MyNumber { get; set; } } public string Result { get; set; } = ""; public MyModel myModel { get; set; } = new(); public async void FormSubmit() { string yourNumber = myModel.MyNumber.HasValue ? myModel.MyNumber.Value.ToString() : "nothing"; Result = $"Your number was {yourNumber}"; }}Component code
@inherits InputBase<int?><div><input type="text" @bind=CurrentValue /></div>@code { protected override bool TryParseValueFromString(string? value, out int? result, out string validationErrorMessage) { validationErrorMessage = ""; result = null; if (string.IsNullOrWhiteSpace(value)) { return true; } int parsedInt; if (!int.TryParse(value.Trim(), out parsedInt)) { validationErrorMessage = "Invalid value!"; return false; } result = parsedInt; return true; }}Updates
- Added the tutorial file from Blazor University to my project, and that same method doesn't get triggered there either. This would appear to be a wider-scale issue therefore.
- Created a new Blazor Server project type (native .Net8) in VS2022 and added the same page. Same failure occurs.
