Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor EditForm and Fluent Validation

Just putting together a wrapper based on EditForm and using Fluent Validation. I've created two properties on this form as below:

if (ModelValidation)
{
    editContext.OnValidationRequested +=
        (sender, eventArgs) => ValidateModel((EditContext)sender, messages);
}

if (FieldValidation)
{
    editContext.OnFieldChanged +=
        (sender, eventArgs) => ValidateField(editContext, messages, eventArgs.FieldIdentifier);
}

This allows validation to be either on OnFieldChanged (value changes, validated on exit field) or when a submit button is pressed (OnValidationRequested)

However, if I have say a text field which is empty (which should be non-empty) tab out of it the OnFieldChanged() handler does not fire...(not surprising the field hasn't changed). Is there a way of forcing the call to OnFieldChanged() or a kill focus handler without resorting to javascript?

like image 488
David S Avatar asked Apr 14 '20 13:04

David S


1 Answers

I thought this was interesting so I took a look at the source code of Blazor's InputText class on the ASP .NET Core project of GitHub here:

https://github.com/dotnet/aspnetcore/blob/master/src/Components/Web/src/Forms/InputText.cs

You'll notice that there is only one event handler and it's for the onchange event raised by the browser when the user changes the value in the text box.

builder.AddAttribute(4, "onchange", EventCallback.Factory.CreateBinder<string>(this, __value => CurrentValueAsString = __value, CurrentValueAsString));

The event you want to subscribe to is onblur, which is raised when the user clicks or tabs out of a field regardless of whether they changed it or not, and it's not been done.

I couldn't find it anywhere in InputText or InputBase (from which InputText derives) but it's there somewhere because this seems to work:

@page "/"
<InputText @onblur="DoSomething" />

@code
{
    private void DoSomething()
    { // Your logic here
    }
}
like image 127
benjamin Avatar answered Oct 16 '22 05:10

benjamin