HTML5 Validation for ASP.NET Core

By FoxLearn 2/27/2025 7:39:02 AM   22
While working on an ASP.NET Core project, I wanted to improve the efficiency of client-server interactions by ensuring that only valid requests were made. This is something HTMX supports by default when you use HTML5 validators on forms and input fields.

However, many ASP.NET Core developers may already know that the default client-side validation system is based on custom data-val attributes and JQuery, rather than using HTML5’s built-in validation. While this method works, it can complicate adopting new frameworks and maintaining additional dependencies.

So, can we replace the JQuery-based validation with HTML5's native validation features? The good news is that Andrew White’s FinBuckle.Html5Validation NuGet package provides a solution for this.

What is HTML5 Validation?

Before HTML5, JavaScript was the go-to solution for client-side form validation. Although JavaScript is powerful, it introduced redundancy in validation code. Developers realized that client-side validation had common patterns and that JavaScript alone wasn’t enough for robust validation, which is why server-side validation remains crucial.

HTML5 shifted the focus of client-side validation to a few core attributes, helping simplify validation while reducing the need for custom scripts. The main HTML5 validation types include:

  • Required: Ensures that the field is filled.
  • Type: Ensures the field matches a specified type, such as a number, date, email, etc.
  • Min/Max: Ensures the field’s value is within a specified range.
  • Pattern: Validates that the input matches a regular expression pattern.

Here’s an example of a form that uses HTML5 validation without requiring any JavaScript:

<form>
  <fieldset>
    <legend>
      Are you a student? <span aria-label="required">*</span>
    </legend>
    <input type="radio" required name="student" id="s1" value="yes" /><label for="s1">Yes</label>
    <input type="radio" required name="student" id="s2" value="no" /><label for="s2">No</label>
  </fieldset>
  
  <p>
    <label for="age">How old are you?</label>
    <input type="number" min="18" max="100" id="age" name="age" required />
  </p>
  
  <p>
    <label for="color">What's your favorite color? <span aria-label="required">*</span></label>
    <input type="text" id="color" name="color" required pattern="Blue|Green|Red|Yellow|Pink" />
  </p>
  
  <p>
    <label for="email">Email Address:</label>
    <input type="email" id="email" name="email" required />
  </p>
  
  <p>
    <label for="message">Leave a message:</label>
    <textarea id="message" name="message" maxlength="200" rows="5"></textarea>
  </p>
  
  <p>
    <button type="submit">Submit</button>
  </p>
</form>

This form uses HTML5 attributes like required, min, max, pattern, and type to handle validation, making JavaScript unnecessary. When submitting the form, the browser checks the fields and prevents submission if the data is invalid.

Disabling Client-Side Validation in ASP.NET Core

If you prefer a more manual approach to writing your views and separating logic from markup, you can disable the default client-side validation in ASP.NET Core MVC or Razor Pages from the Program.cs file:

builder.Services.AddRazorPages()
    .AddViewOptions(options => {
        options.HtmlHelperOptions.ClientValidationEnabled = false;
    });

This will prevent the generation of the data-val attributes on form inputs, which are typically used for the default validation.

While this approach works, the next solution might be more suitable for most scenarios, especially if you want to retain ASP.NET Core's model metadata for validation.

Using the FinBuckle.HTML5Validation NuGet Package

To move towards HTML5 validation in your ASP.NET Core project, you can install the NuGet package. This package allows you to use HTML5 validation without removing the benefits of model metadata that ASP.NET Core provides.

First, install the package:

<PackageReference Include="Finbuckle.Html5Validation" Version="1.0.1" />

Then, register the package with your application:

using Finbuckle.Html5Validation;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHtml5Validation();

This will set up the necessary infrastructure for HTML5 validation in your project, utilizing the model metadata and keeping everything clean.

Implementing HTML5 Validation in Razor Views

Let's see how we can use HTML5 validation in a Razor Page.

Here's an example of a PageModel with validation attributes:

using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace MyApp.Pages;

public class ContactModel(ILogger<ContactModel> logger) : PageModel
{
    [BindProperty, Required]
    public string? FullName { get; set; }
    
    [BindProperty, Required]
    public string? FavoriteMusic { get; set; }
    
    [BindProperty, Range(18, 100)]
    public int? Age { get; set; }

    public void OnGet()
    {
    }

    public IActionResult OnPost()
    {
        if (ModelState.IsValid)
        {
            logger.LogInformation("{FullName} likes {FavoriteMusic}", FullName, FavoriteMusic);
        }

        return Partial("_Form", this);
    }
}

Now, let’s look at the Razor view. In this case, we’ll use HTMX to handle the form submission and swap the content dynamically:

@model ContactModel

<form method="post" asp-page="Contact"
      hx-post="@Url.Page("Contact")"
      hx-swap="outerHtml">

    <div class="form-group">
        <label asp-for="FullName"></label>
        <input asp-for="FullName" class="form-control" />
    </div>

    <div class="form-group">
        <label asp-for="FavoriteMusic"></label>
        <input asp-for="FavoriteMusic" class="form-control" />
    </div>

    <div class="form-group">
        <label asp-for="Age"></label>
        <input asp-for="Age" class="form-control" type="number" />
    </div>

    <button type="submit" class="btn btn-primary">Submit</button>
</form>

Here, the model properties are bound to the form fields, and ASP.NET Core will automatically generate the necessary HTML5 validation attributes for each field.

CSS Styling for Invalid Fields

Finally, let's add some CSS to provide feedback to users when they enter invalid data:

input:invalid {
    border-color: red;
    background-color: lightpink;
    box-shadow: 0 0 5px 1px red;
}

input:valid {
    border-color: green;
    background-color: lightgreen;
}

These styles will highlight the input fields with red borders when the user enters invalid data, and with green when the input is valid.

HTML5 validation is a powerful tool that simplifies client-side validation and reduces the need for complex JavaScript. By leveraging the FinBuckle.Html5Validation NuGet package, you can enhance your ASP.NET Core MVC or Razor Pages application with native HTML5 validation without relying on external libraries like JQuery.