Learn Blazor · 8/15

Forms & Data Validation

8 min read

Forms & Data Validation

Welcome to Module 8! 🚀

Let’s be honest for a second. The internet is essentially a series of fancy pipes designed to move data from a user's brain into a database. How do we bridge that gap? Forms.

Login screens, checkout pages, search bars, that weird survey asking if you prefer tabs or spaces—they are all forms. Without them, the web is just a digital brochure.

In traditional web development, handling forms is often a tedious dance of:

  1. Grabbing values from the DOM.
  2. Converting strings to numbers/dates.
  3. Writing 50 if statements to check if the email actually looks like an email.
  4. Displaying error messages without making the UI look like a ransom note.

Blazor takes this pain and replaces it with the EditForm component and Data Annotations. It’s like trading a rusty bicycle for a Tesla.

Let's dive in. 🌊


1. The EditForm Component: Blazor's Form Engine

Definition

The EditForm is a built-in Blazor component that renders a standard HTML <form> element but creates an EditContext to track the state of the form's data (whether fields have been modified, if they are valid, etc.).

The Problem

In standard HTML, a <form> submits data to a URL, causing a full page reload. In a Single Page Application (SPA) like Blazor, we don't want reloads. We want to intercept that submission, check the data, and send it to an API seamlessly. Doing this manually requires preventing default browser events and manually tracking every input field's value.

The Solution

EditForm wraps your input fields. It prevents the default page reload automatically and sets up a data binding context.

How to use it

To use an EditForm, you need a "Model"—a C# object that holds the data you want the user to edit.

csharp
@page "/starship-entry"

<h3>New Starship Registration</h3>

<!-- The Model parameter binds the form to our C# object -->
<EditForm Model="@starship">
    <p>Form content goes here...</p>
    <button type="submit">Launch!</button>
</EditForm>

@code {
    // This is our model
    public class Starship
    {
        public string Identifier { get; set; }
        public string Captain { get; set; }
        public int CrewCount { get; set; }
    }

    private Starship starship = new Starship();
}

Under the Hood:
When EditForm initializes, it creates an EditContext. This context is the brain. It watches the starship object. If you change a property in the C# object, the form updates. If you change a field in the form, the C# object updates.

Fun Fact: If you accidentally use a standard HTML <form> tag in Blazor without method="post", Blazor might yell at you. It really wants you to use EditForm because it loves you and wants you to be safe. 🛡️


2. Using Built-in Input Components

Definition

Blazor provides specialized components that wrap standard HTML input elements (like <input>, <select>, <textarea>). These components (e.g., InputText, InputNumber) provide built-in two-way data binding and automatic CSS class toggling for validation states.

The Problem

You could use standard HTML inputs:

html
<input value="@starship.Identifier" @onchange="@((ChangeEventArgs e) => starship.Identifier = e.Value.ToString())" />

This is awful. It's verbose, handles types poorly (everything is a string in HTML), and doesn't know when to turn red if the data is invalid.

The Solution

Blazor's built-in components handle the type conversion (String to Int, etc.) and bind directly to your model.

The Component List

Here are the industry standards you will use 99% of the time:

Blazor Component Renders HTML Use Case
<InputText> <input type="text"> Names, Titles, short strings.
<InputTextArea> <textarea> Bios, Descriptions, long rants.
<InputNumber> <input type="number"> Integers, Decimals, Floats.
<InputCheckbox> <input type="checkbox"> Booleans (True/False).
<InputSelect> <select> Dropdowns.
<InputDate> <input type="date"> DateTime objects.

Practical Example

Let's flesh out our Starship form. Note the use of @bind-Value.

razor
<EditForm Model="@starship">
    
    <div>
        <label>Ship Identifier:</label>
        <!-- Binds directly to the string -->
        <InputText @bind-Value="starship.Identifier" class="form-control" />
    </div>

    <div>
        <label>Crew Count:</label>
        <!-- Automatically parses the input to an integer -->
        <InputNumber @bind-Value="starship.CrewCount" class="form-control" />
    </div>

    <div>
        <label>Is Commissioned:</label>
        <InputCheckbox @bind-Value="starship.IsCommissioned" />
    </div>

    <button type="submit">Submit</button>
</EditForm>

Key Feature:
When the user types in these fields, Blazor automatically applies CSS classes to the input element:

  • valid: The data is good.
  • invalid: The data breaks a rule.
  • modified: The user touched this field.

This allows you to style invalid fields with a red border easily in your CSS.


3. Data Annotations: Validating Models

Definition

Data Annotations are C# attributes (found in System.ComponentModel.DataAnnotations) that you place above class properties to define validation rules declaratively.

The Problem

Imagine writing validation logic manually inside your submit function:

csharp
if (string.IsNullOrEmpty(starship.Identifier)) { Error = "Name is required"; return; }
if (starship.CrewCount < 0) { Error = "You can't have negative crew"; return; }
if (starship.CrewCount > 10000) { Error = "Too many people!"; return; }

This is "Spaghetti Code." It mixes your UI logic with business rules. It is hard to read and harder to maintain.

The Solution

We define the rules on the model itself. The form simply enforces them.

To enable this, we need to add two components inside our EditForm:

  1. <DataAnnotationsValidator />: Enables the validation engine.
  2. <ValidationSummary />: Displays a list of all errors (optional, but good for debugging).

Updated Model & Form

First, update the C# class with attributes.

csharp
using System.ComponentModel.DataAnnotations; // Don't forget this!

public class Starship
{
    [Required(ErrorMessage = "Every ship needs a name, Captain.")]
    [StringLength(20, ErrorMessage = "Identifier is too long.")]
    public string Identifier { get; set; }

    [Required]
    [Range(1, 5000, ErrorMessage = "Crew must be between 1 and 5000.")]
    public int CrewCount { get; set; }

    [Required]
    [EmailAddress] // Checks for @ format automatically
    public string CaptainEmail { get; set; }
}

Now, update the component:

razor
<EditForm Model="@starship">
    <!-- 1. Enable Validation -->
    <DataAnnotationsValidator />
    
    <!-- 2. Show all errors in a list -->
    <ValidationSummary />

    <div>
        <label>Identifier:</label>
        <InputText @bind-Value="starship.Identifier" />
        <!-- Show error for THIS specific field only -->
        <ValidationMessage For="@(() => starship.Identifier)" />
    </div>

    <div>
        <label>Crew Count:</label>
        <InputNumber @bind-Value="starship.CrewCount" />
        <ValidationMessage For="@(() => starship.CrewCount)" />
    </div>

    <button type="submit">Submit</button>
</EditForm>

What happens here?
If a user tries to enter "-5" for the Crew Count, the <ValidationMessage> component will immediately display "Crew must be between 1 and 5000" and the input box gets the .invalid CSS class.

Imagination Time: Think of DataAnnotationsValidator as the security guard at a club. The Attributes (rules) are the dress code. The EditForm is the entrance. If you show up wearing flip-flops (invalid data), the security guard points to the sign and says "Not today."


4. Handling Valid, Invalid, and Raw Form Submissions

Definition

These are the event callbacks provided by EditForm that trigger when the user triggers a submit (usually by pressing a button with type="submit").

The Problem

We need to know the result of the validation before we send data to our database. If we just used a generic OnSubmit, we would have to manually check EditContext.Validate() every time.

The Solution

Blazor gives us three specific events. You usually only use one of them.

  1. OnValidSubmit (The Golden Path 🌟): Triggered only if validation passes.
  2. OnInvalidSubmit: Triggered if validation fails.
  3. OnSubmit: Triggered regardless of validity. (If you use this, you cannot use the other two).

Industry Practice: The Happy Path

In 95% of real-world applications, you will use OnValidSubmit. You don't usually need to run code when the form is invalid (the UI already shows the red error messages automatically).

razor
<EditForm Model="@starship" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />
    <!-- Inputs here -->
    <button type="submit">Launch</button>
</EditForm>

@code {
    private void HandleValidSubmit()
    {
        // This code ONLY runs if the data is perfect.
        // Save to database, call API, etc.
        Console.WriteLine("Starship is ready for launch!");
    }
}

When to use OnSubmit?

Use OnSubmit only if you have complex, custom validation logic that cannot be handled by Data Annotations (e.g., you need to check the database asynchronously to see if the "Ship Identifier" is already taken before allowing submission).

csharp
private async Task HandleSubmit(EditContext context)
{
    // Manual check
    if (context.Validate())
    {
        // Do save logic
    }
    else
    {
        // Log validation error
    }
}

Summary 📝

  1. EditForm is the container. It tracks the state of your data.
  2. InputComponents (InputText, InputNumber) are your fields. They handle types and CSS classes automatically.
  3. Data Annotations ([Required]) are your rules. They keep bad data out.
  4. OnValidSubmit is your gatekeeper. It ensures your backend logic only runs when data is clean.

Forms used to be hard. Now they are just a matter of "fill in the blanks" with components. Go forth and validate!

References & Further Reading 📚

Challenge

You are given an array of product objects.

Write a JavaScript function named processProducts that takes one argument: an array of product objects.

Each product object has the following structure: { id: number, name: string, category: string, price: number, inStock: boolean }.

Your function must perform the following tasks:

  1. Filter the array to keep only the products that belong to the 'Electronics' category and are inStock.
  2. From this filtered list, create a new array of strings. Each string should be in the format: '<product.name>: $<product.price>'.
  3. Calculate the sum of the prices of all the filtered products.
  4. The function must return an object with two properties: productSummaries (the array of strings from step 2) and totalValue (the total cost from step 3).

Expected result

The processProducts function should be implemented to correctly filter and process the input array.

When invoked with the provided products array, the function is expected to return an object with the following structure and values:

json
{
  "productSummaries": [
    "Laptop: $1200",
    "Monitor: $300",
    "Webcam: $80"
  ],
  "totalValue": 1580
}
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.