Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

TryParseValueFromString not being triggered

$
0
0

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:

enter image description here

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<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;    }}

Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>