Course contentsShow
← C#
Lesson 1401 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Data Validation Decorators

Create reusable validation decorators that clean and format user input automatically.

Data Validation Decorators: Cleaning Input Before it Hits Your Model

In this lesson, you will learn how to build reusable validation decorators that automatically clean and format user input before it binds to your application state.

When building Blazor forms, we often deal with "messy" user input—trailing spaces, inconsistent casing, or malformed phone numbers. Rather than polluting your setters with repetitive logic or cluttering your components with "on-blur" cleanup methods, we can use Data Validation Decorators.

The Decorator Pattern for Data

Think of a decorator as a protective shell around your data properties. By creating custom ValidationAttribute classes, we can intercept the value as it’s being validated. While standard attributes like [Required] or [Range] check if data is valid, custom decorators can actually mutate or sanitize the input during the validation lifecycle.

Consider a requirement where a user input for a "Display Name" must be trimmed of whitespace and converted to title case:

public class TitleCaseAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value is string str)
        {
            var property = validationContext.ObjectType.GetProperty(validationContext.MemberName);
            var sanitized = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.Trim().ToLower());
            
            // Mutate the property directly
            property?.SetValue(validationContext.ObjectInstance, sanitized);
        }
        return ValidationResult.Success;
    }
}

Applying the Logic

Once defined, you simply "decorate" your model properties:

public class UserProfile
{
    [TitleCase]
    [Required]
    public string DisplayName { get; set; }
}

When Blazor’s EditContext triggers validation (usually on submit or focus loss), the TitleCase decorator runs. It cleans the input, updates the model property directly via reflection, and ensures your backend receives only pristine, formatted data.

This approach keeps your UI components clean because they remain purely focused on rendering, while your domain models handle their own hygiene. By moving this logic into reusable attributes, you eliminate "logic drift" across different forms in your application, ensuring consistent formatting whether the user is signing up or editing their account settings.

Key Takeaway: Use data validation decorators to centralize input sanitization logic, ensuring your models stay clean and consistent without repeating cleanup code in your Blazor components.