--- name: blazor-forms-validation description: Blazor forms, EditForm, input components, DataAnnotations, FluentValidation, and custom validation allowed-tools: - Read - Write - Edit - Grep triggers: - blazor form - EditForm - validation - DataAnnotations - FluentValidation - input component --- # Blazor Forms and Validation ## EditForm Setup ```razor @rendermode InteractiveServer
@foreach (var cat in _categories) { }
``` ## Model with DataAnnotations ```csharp public sealed class CreateItemModel { [Required(ErrorMessage = "Name is required")] [StringLength(200, MinimumLength = 2)] public string Name { get; set; } = ""; [Required, EmailAddress] public string Email { get; set; } = ""; [Range(1, int.MaxValue, ErrorMessage = "Select a category")] public int CategoryId { get; set; } [Range(typeof(bool), "true", "true", ErrorMessage = "Must accept terms")] public bool AcceptTerms { get; set; } } ``` ## FluentValidation Integration ```csharp // Install: Blazored.FluentValidation public sealed class CreateItemValidator : AbstractValidator { public CreateItemValidator() { RuleFor(x => x.Name) .NotEmpty().WithMessage("Name is required") .MaximumLength(200); RuleFor(x => x.Email) .NotEmpty().EmailAddress(); RuleFor(x => x.CategoryId) .GreaterThan(0).WithMessage("Select a category"); } } ``` ```razor @using Blazored.FluentValidation @* ... inputs ... *@ ``` ## SSR Form Handling (.NET 10) For static SSR pages, use `[SupplyParameterFromForm]`: ```razor @page "/items/create" @* inputs *@ @code { [SupplyParameterFromForm] private CreateItemModel Model { get; set; } = new(); private async Task HandleSubmit() { await ItemService.CreateAsync(Model); Navigation.NavigateTo("/items"); } } ``` ## Input Components | Component | Binds to | HTML | |-----------|---------|------| | `InputText` | `string` | `` | | `InputTextArea` | `string` | `