Today we will tackle Blazor Forms and Validation, now for keeping things simple we will stick to what is on the official documentation. By now I assume that you already have all Blazor dependency setup. We’ll star by creating a new Blazor project.

Note: Forms and validation scenarios are likely to change with each preview release.

Blazor uses Data annotation to define validation logic. Here’s a class I created to validate a user signup.

using System.ComponentModel.DataAnnotations;
using BlazorValidation.Shared.Models;

namespace BlazorValidation.Shared.Validations
{
    public class SignUpFormValidation
    {

        [Required(ErrorMessage ="first name is required.")]
        [StringLength(10, ErrorMessage = "first name is too long.")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "last name is required.")]
        [StringLength(10, ErrorMessage = "last name is too long.")]
        public string LastName { get; set; }

        [Required(ErrorMessage = "age is required.")]
        [Range(13,200, ErrorMessage ="must be 13 or older")]
        public int Age { get; set; }

        [Required(ErrorMessage = "username is required.")]
        [MinLength(4, ErrorMessage = "username must be at least 4 characters")]
        public string Username { get; set; }

        [Required(ErrorMessage = "email is required.")]
        [EmailAddress()]
        public string Email { get; set; }

        [Required(ErrorMessage = "password is required.")]
        [MinLength(8, ErrorMessage = "password must be atleast 8 characters")]
        [DataType(DataType.Password)]
        public string Password { get; set; } = string.Empty;

        [Required(ErrorMessage = "re-type password is required.")]
        [Compare(nameof(Password), ErrorMessage = "password dosent match")]
        public string ConfirmPassword { get; set; } = string.Empty;

        public User GetRegisteredUser()
        {
            return new User
            {
            FirstName =FirstName,
            LastName = LastName,
            Age =Age,
            Username = Username,
            Email = Email,
            Password = Password,
            ConfirmPassword =ConfirmPassword
            };
        }
    }
}

We specified the validation we want to have for each property, you can also specify the error message you want to be displayed.

Now we create a razor page, in here we’ll add the form Blazor defines form using the ‘EditForm’ component. Here a ‘EditForm’ that uses the validation class we just created.

<h4 class="mb-3">Sign Up</h4>
                <EditForm class="needs-validation" Model="@_validation" onValidSubmit="@OnValidSubmit" onInvalidSubmit="@OnInvalidSubmit" novalidate>
                    <DataAnnotationsValidator />
                    @*<ValidationSummary />*@
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="firstName">First Name</label>
                            <InputText type="text" class="form-control" id="firstName" @bind-value="_validation.FirstName" placeholder="" />
                            <ValidationMessage For="@(() => @_validation.FirstName)" />

                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="lastName">Last Name</label>
                            <InputText type="text" class="form-control" id="lastName" @bind-value="_validation.LastName" placeholder="" />
                            <ValidationMessage For="@(() => @_validation.LastName)" />
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="username">Username</label>
                        <div class="input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text"></span>
                            </div>
                            <InputText type="text" @bind-value="_validation.Username" class="form-control" id="username" placeholder="Username" />
                            <ValidationMessage For="@(() => @_validation.Username)" />
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="username">Age</label>
                        <div class="input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text"></span>
                            </div>
                            <InputNumber type="text" @bind-value="_validation.Age" class="form-control" id="age" placeholder="18" />
                            <ValidationMessage For="@(() => @_validation.Age)" />
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="email">Email</label>
                        <InputText type="email" class="form-control" @bind-value="_validation.Email" id="email" placeholder="you@example.com" />
                        <ValidationMessage For="@(() => @_validation.Email)" />
                    </div>
                    <div class="mb-3">
                        <label for="password">Password</label>
                        <InputText type="password" class="form-control" @bind-value="_validation.Password" id="password" placeholder="********" />
                        <ValidationMessage For="@(() => @_validation.Password)" />
                    </div>
                    <div class="mb-3">
                        <label for="confirm-password">Confirm Password</label>
                        <InputText type="password" class="form-control" id="confirm-password" @bind-value="_validation.ConfirmPassword" placeholder="********" />
                        <ValidationMessage For="@(() => @_validation.ConfirmPassword)" />
                    </div>

                    <hr class="mb-4">
                    <button class="btn btn-primary btn-lg btn-block" type="submit">Sign Up</button>
                </EditForm>

@code {
private SignUpFormValidation _validation = new SignUpFormValidation();
//This will trigger when the form was valid
private void OnValidSubmit()
{
    Console.WriteLine("Submit Valid");
}

//This will trigger when the form was invalid
public void OnInvalidSubmit()
{
    Console.WriteLine("Submit Invalid");
}

Let’s break down what’s on the EditForm

  • Model – This is the validation logic that we created
  • OnValidSubmit – this will be call when the submit is valid
  • OnInvalidSubmit – This will be call when the submit is invalid
  • OnSubmit – This will be call when user submit(if you choose to use Onsubmit you will need to check the validation yourself. Since OnValidSubmit and OnInvalidSubmit can bu use if you use OnSubmit)
  • DataAnnotationsValidator – Attaches validation support using data annotations.
  • ValidationSummary –  Summarizes validation messages
  • ValidationSummary – Will only show validation message from a specific field.

Blazor already comes with components that support receiving and validate user input:

  • InputText – it will render has <input>
  • InputTextArea – it will render has <textarea>
  • InputSelect – it will render has <select>
  • InputNumber – it will render has <input type=”number”>
  • InputCheckbox – it will render has <input type=”checkbox”>
  • InputDate – it will render has <input type=”date”>

Input components provide default behavior for validating on edit and changing their CSS class to reflect the field state. Some components include useful parsing logic. For example, InputDate and InputNumber handle unparseable values gracefully by registering them as validation errors. Types that can accept null values also support nullability of the target field.

Here is the result of our sign-up form

You can see that the EditForm component takes care of the styling of the form.

This will give you a basic understanding on validation for a registration form. To put this to the test I created an actual repo that have all that I show you in this tutorial and has a Log in page to log in once you sign up.

If you need help on working with Blazor, leave a comment and I will gladly try to help you with anything I can. For more blogpost like this, visit nativoplus.studio/blog