Mudblazor
Toggle light/dark theme
GitHub repository
Toggle right-to-left/left-to-right

Form Validation

All about checking user input and visualization of errors.

See Form Validation API for parameter documentation.

Simple Form Validation

MudForm is designed to be easy and simple. You just pass your own validation functions directly into the Validation parameter of your input controls. But if you want to make use of the handy data annotation attributes provided by Microsoft, you can pass them into Validation also. You can even use FluentValidation as is shown in another example below.

Note: for MudForm, do NOT use a button with ButtonType="ButtonType.Submit"

Choose a strong password

Repeat the password

Show Errors (0)
Show code example
Copy Code
View the source on GitHub
@using System.Text.RegularExpressions
@using System.ComponentModel.DataAnnotations


<div style="max-width: 400px;">
    <MudCard>
        <MudCardContent>
            <MudForm @ref="form" @bind-IsValid="@success" @bind-Errors="@errors">
                <MudTextField T="string" Label="Username" Required="true" RequiredError="User name is required!"/>
                <MudTextField T="string" Class="mt-3" Label="Email" Required="true" RequiredError="Email is required!"
                              Validation="@(new EmailAddressAttribute() {ErrorMessage = "The email address is invalid"})"/>
                <MudTextField T="string" Class="mt-3" Label="Password" HelperText="Choose a strong password" @ref="pwField1"
                              InputType="InputType.Password"
                              Validation="@(new Func<string, IEnumerable<string>>(PasswordStrength))" Required="true"
                              RequiredError="Password is required!"/>
                <MudTextField T="string" Class="mt-3"
                              Label="Password" HelperText="Repeat the password" InputType="InputType.Password"
                              Validation="@(new Func<string, string>(PasswordMatch))"/>
                <MudCheckBox T="bool" Required="true" RequiredError="You must agree" Class="ml-n2"
                             Label="I agree that MudBlazor is awesome!"/>
            </MudForm>
        </MudCardContent>
        <MudCardActions>
            <MudButton Variant="Variant.Filled" Color="Color.Primary" Disabled="@(!success)" Class="ml-auto">Register</MudButton>
        </MudCardActions>
    </MudCard>
    
    <MudPaper Class="pa-4 justify-center my-4 mud-text-align-center">
        <MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@(()=>form.Validate())">Validate</MudButton>
        <MudButton Variant="Variant.Filled" Color="Color.Secondary" OnClick="@(()=>form.Reset())" Class="mx-2">Reset</MudButton>
        <MudButton Variant="Variant.Filled" OnClick="@(()=>form.ResetValidation())">Reset Validation</MudButton>
    </MudPaper>

    <MudExpansionPanels>
        <MudExpansionPanel Text="@($"Show Errors ({errors.Length})")">
            @foreach (var error in errors)
            {
                <MudText Color="@Color.Error">@error</MudText>
            }
        </MudExpansionPanel>
    </MudExpansionPanels>
</div>
@code {
    bool success;
    string[] errors = { };
    MudTextField<string> pwField1;
    MudForm form;

    private IEnumerable<string> PasswordStrength(string pw)
    {
        if (string.IsNullOrWhiteSpace(pw))
        {
            yield return "Password is required!";
            yield break;
        }
        if (pw.Length < 8)
            yield return "Password must be at least of length 8";
        if (!Regex.IsMatch(pw, @"[A-Z]"))
            yield return "Password must contain at least one capital letter";
        if (!Regex.IsMatch(pw, @"[a-z]"))
            yield return "Password must contain at least one lowercase letter";
        if (!Regex.IsMatch(pw, @"[0-9]"))
            yield return "Password must contain at least one digit";
    }

    private string PasswordMatch(string arg)
    {
        if (pwField1.Value != arg)
            return "Passwords don't match";
        return null;
    }

}

EditForm Support

In Blazor form validation is usually done with EditForm in conjunction with a form model class that is decorated with data annotations. MudBlazor's input components support Blazor's form validation if you put them into a <EditForm>. The following example shows a very simple use case. If you want to learn more please check out ASP.NET Core Blazor forms and validation on the official Blazor documentation.

Note: for EditForm validation to work make sure to set ButtonType="ButtonType.Submit" and do not use a MudForm.

Max. 8 characters

Choose a strong password

Repeat the password

Fill out the form correctly to see the success message.

Show Validation Summary

Show code example
Copy Code
View the source on GitHub
@using System.ComponentModel.DataAnnotations

<div style="max-width: 400px;">
    <EditForm Model="@model" OnValidSubmit="OnValidSubmit">
        <DataAnnotationsValidator />
        <MudCard>
            <MudCardContent>
                <MudTextField Label="First name" HelperText="Max. 8 characters"
                              @bind-Value="model.Username" For="@(() => model.Username)" />
                <MudTextField Label="Email" Class="mt-3"
                              @bind-Value="model.Email" For="@(() => model.Email)" />
                <MudTextField Label="Password" HelperText="Choose a strong password" Class="mt-3"
                              @bind-Value="model.Password" For="@(() => model.Password)" InputType="InputType.Password" />
                <MudTextField Label="Password" HelperText="Repeat the password" Class="mt-3"
                              @bind-Value="model.Password2" For="@(() => model.Password2)" InputType="InputType.Password" />
            </MudCardContent>
            <MudCardActions>
                <MudButton ButtonType="ButtonType.Submit" Variant="Variant.Filled" Color="Color.Primary" Class="ml-auto">Register</MudButton>
            </MudCardActions>
        </MudCard>
        <MudText Typo="Typo.body2" Align="Align.Center" Class="my-4">
            Fill out the form correctly to see the success message.
        </MudText>

        <MudExpansionPanels>
            <MudExpansionPanel Text="Show Validation Summary">
                @if (success)
                {
                    <MudText Color="Color.Success">Success</MudText>
                }
                else
                {
                    <MudText Color="@Color.Error">
                        <ValidationSummary />
                    </MudText>
                }
            </MudExpansionPanel>
        </MudExpansionPanels>
    </EditForm>
</div>
@code {
    RegisterAccountForm model = new RegisterAccountForm();
    bool success;

    public class RegisterAccountForm
    {
        [Required]
        [StringLength(8, ErrorMessage = "Name length can't be more than 8.")]
        public string Username { get; set; }

        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        [StringLength(30, ErrorMessage = "Password must be at least 8 characters long.", MinimumLength = 8)]
        public string Password { get; set; }

        [Required]
        [Compare(nameof(Password))]
        public string Password2 { get; set; }

    }

    private void OnValidSubmit(EditContext context)
    {
        success = true;
        StateHasChanged();
    }

}

Using Fluent Validation

This example shows how to make use of the powerful FluentValidation validators with MudForm. Basically, we call the validator in our validation func and simply return the error messages.

Show code example
Copy Code
View the source on GitHub
@using FluentValidation

<div style="max-width: 400px;">
    <MudCard>
        <MudCardContent>
            <MudForm>
                <MudTextField @bind-Value="creditCardNr"
                              Validation="@validationFunc"
                              Immediate="true"
                              Label="Credit card nr" />
            </MudForm>
        </MudCardContent>
    </MudCard>
</div>
@code { 
    // this is a valid test Visa card number
    string creditCardNr = "4012 8888 8888 1881";

    // This is a FluentValidation validator which we'll use to validate above MudTextfield
    public class CreditCardValidator : AbstractValidator<string>
    {
        public CreditCardValidator() => RuleFor(x => x).CreditCard();
    }

    // Create a MudBlazor-esque validation func based on the fluent validator.
    Func<string, IEnumerable<string>> validationFunc = new Func<string, IEnumerable<string>>(input =>
    {
        var validator = new CreditCardValidator();
        var result = validator.Validate(input);
        if (result.IsValid)
            return new string[0];
        return result.Errors.Select(e => e.ErrorMessage);
    });
}
An error has occurred. This application may no longer respond until reloaded. Reload 🗙