Form Validation

All about checking user input and visualization of errors.

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, as well. You can even use FluentValidation as shown in one of the examples below.

Choose a strong password

Repeat the password

Errors (0)
@using System.Text.RegularExpressions
@using System.ComponentModel.DataAnnotations

<MudGrid>
    <MudItem xs="12" sm="7">
        <MudPaper Class="pa-4">
            <MudForm @ref="form" @bind-IsValid="@success" @bind-Errors="@errors">
                <MudTextField T="string" Label="Username" Required="true" RequiredError="User name is required!" />
                    <MudTextField T="string" Label="Email" Required="true" RequiredError="Email is required!"
                              Validation="@(new EmailAddressAttribute() {ErrorMessage = "The email address is invalid"})" />
                    <MudTextField T="string" 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"
                                  Label="Password" HelperText="Repeat the password" InputType="InputType.Password"
                                  Validation="@(new Func<string, string>(PasswordMatch))"/>
                    <div class="d-flex">
                        <MudRadioGroup T="string" Required="true" RequiredError="Account type is required!">
                            <MudRadio Value="@("Personal")">Personal</MudRadio>
                            <MudRadio Value="@("Professional")">Professional</MudRadio>
                        </MudRadioGroup>
                    </div>
                    <div class="d-flex align-center justify-space-between">
                        <MudCheckBox T="bool" Required="true" RequiredError="You must agree" Label="I agree!"  />
                        <MudButton Variant="Variant.Filled" Color="Color.Primary" Disabled="@(!success)" Class="ml-auto">Register</MudButton>
                    </div>
            </MudForm>   
        </MudPaper>
        <MudPaper Class="pa-4 mt-4">
            <MudButton Variant="Variant.Filled" Color="Color.Primary" DisableElevation="true" OnClick="@(()=>form.Validate())">Validate</MudButton>
            <MudButton Variant="Variant.Filled" Color="Color.Secondary" DisableElevation="true" OnClick="@(()=>form.ResetAsync())" Class="mx-2">Reset</MudButton>
            <MudButton Variant="Variant.Filled" DisableElevation="true" OnClick="@(()=>form.ResetValidation())">Reset Validation</MudButton>
        </MudPaper>
    </MudItem>
    <MudItem xs="12" sm="5">
        <MudPaper Class="pa-4 mud-height-full">
            <MudText Typo="Typo.subtitle2">@($"Errors ({errors.Length})")</MudText>
                @foreach (var error in errors)
                {
                    <MudText Color="@Color.Error">@error</MudText>
                }
        </MudPaper>
    </MudItem>
</MudGrid>
@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.

Max. 8 characters

Choose a strong password

Repeat the password

Validation Summary

Fill out the form correctly to see the success message.

@using System.ComponentModel.DataAnnotations

<EditForm Model="@model" OnValidSubmit="OnValidSubmit">
<DataAnnotationsValidator/>
<MudGrid>
    <MudItem xs="12" sm="7">
        <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>
    </MudItem>
    <MudItem xs="12" sm="5">
        <MudPaper Class="pa-4 mud-height-full">
            <MudText Typo="Typo.subtitle2">Validation Summary</MudText>
            @if (success)
            {
                <MudText Color="Color.Success">Success</MudText>
            }
            else
            {
                <MudText Color="@Color.Error">
                    <ValidationSummary />
                </MudText>
            }
        </MudPaper>
    </MudItem>
    <MudItem xs="12">
        <MudText Typo="Typo.body2" Align="Align.Center">
            Fill out the form correctly to see the success message.
        </MudText>
    </MudItem>
</MudGrid>
</EditForm>
@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 Simple Fluent Validation

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

@using FluentValidation

<MudPaper Class="pa-4">
    <MudForm>
        <MudTextField @bind-Value="creditCardNr" Validation="@ccValidator.Validation" Immediate="true" Label="Credit card nr" />
    </MudForm>
</MudPaper>
@code { 
    // This is a valid Visa test card number
    string creditCardNr = "4012 8888 8888 1881";

    // The validation rules (overkill, I know, but very fluent):
    FluentValueValidator<string> ccValidator = new FluentValueValidator<string>(x => x
        .NotEmpty()
        .Length(1,100)
        .CreditCard());

    /// <summary>
    /// A glue class to make it easy to define validation rules for single values using FluentValidation
    /// You can reuse this class for all your fields, like for the credit card rules above.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class FluentValueValidator<T> : AbstractValidator<T>
    {
        public FluentValueValidator(Action<IRuleBuilderInitial<T, T>> rule)
        {
            rule(RuleFor(x => x));
        }

        private IEnumerable<string> ValidateValue(T arg)
        {
            var result = Validate(arg);
            if (result.IsValid)
                return new string[0];
            return result.Errors.Select(e => e.ErrorMessage);
        }

        public Func<T, IEnumerable<string>> Validation => ValidateValue;
    }
}

Copyright © 2020-2024 MudBlazor.

Powered by .NET 8.0.8

An error has occurred. This application may no longer respond until reloaded. Reload 🗙