Search code examples
blazormudblazor

Determine whether MudTextField is valid without updating UI


I'm using Blazor and MudBlazor.

If I call myMudTextField.Validate() then it validates the field and updates the UI - shows validation errors, etc.

Can I determine whether the field is valid without updating the UI? For example, something like myMudTextField.IsValid.


Solution

  • I think you can implement custom validations with the use of yields as a field validation, if that's what you need. Here it's an example of how i use it!

    Page.razor:

    <MudTextField Validation="@(new Func<int, IEnumerable<string>>(PtoVtaStrength))" T="int" Pattern="^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$" Placeholder="123"  Required="true" RequiredError="PtoVta required" Text="@PtoVta.ToString()" />
    

    Page.razor.cs

    private IEnumerable<string> PtoVtaStrength(int value)
    {
        if (value <= 0)
        {
            yield return "IsValid";
            yield break;
        }
    }
    

    UPDATE:

    If you want to check if it's valid or not with mud blazor, at the moment you need to implement custom validation On property changed!

    Page.Razor:

    <MudTextField Validation="@(new Func<int, IEnumerable<string>>(PtoVtaStrength))" T="int" Placeholder="123"  Required="true" RequiredError="Punto de venta requerido" ValueChanged="@OnPtoVtaChanged" Text="@PtoVta.ToString()" />
    

    Page.razor.cs:

    private Task OnPtoVtaChanged(int value)
    {
        //Do your validation here
        //if true
        PtoVta = value;
        //else
        PtoVta = 0
        return Task.CompletedTask;
    }