From 860d795623accc32d639e750de9727c882950c72 Mon Sep 17 00:00:00 2001 From: Luke Latham Date: Thu, 17 Sep 2020 07:58:36 -0500 Subject: [PATCH] Blazor custom validation class attributes (#19909) --- aspnetcore/blazor/forms-validation.md | 28 ++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/aspnetcore/blazor/forms-validation.md b/aspnetcore/blazor/forms-validation.md index 4dcddb8197..cfc1953794 100644 --- a/aspnetcore/blazor/forms-validation.md +++ b/aspnetcore/blazor/forms-validation.md @@ -5,7 +5,7 @@ description: Learn how to use forms and field validation scenarios in Blazor. monikerRange: '>= aspnetcore-3.1' ms.author: riande ms.custom: mvc -ms.date: 08/18/2020 +ms.date: 09/17/2020 no-loc: ["ASP.NET Core Identity", cookie, Cookie, Blazor, "Blazor Server", "Blazor WebAssembly", "Identity", "Let's Encrypt", Razor, SignalR] uid: blazor/forms-validation --- @@ -1015,6 +1015,32 @@ private class CustomValidator : ValidationAttribute > [!NOTE] > is `null`. Injecting services for validation in the `IsValid` method isn't supported. +::: moniker range=">= aspnetcore-5.0" + +## Custom validation class attributes + +Custom validation class names are useful when integrating with CSS frameworks, such as [Bootstrap](https://getbootstrap.com/). To specify custom validation class names, create a class derived from `FieldCssClassProvider` and set the class on the instance: + +```csharp +var editContext = new EditContext(model); +editContext.SetFieldCssClassProvider(new MyFieldClassProvider()); + +... + +private class MyFieldClassProvider : FieldCssClassProvider +{ + public override string GetFieldCssClass(EditContext editContext, + in FieldIdentifier fieldIdentifier) + { + var isValid = !editContext.GetValidationMessages(fieldIdentifier).Any(); + + return isValid ? "good field" : "bad field"; + } +} +``` + +::: moniker-end + ### Blazor data annotations validation package The [`Microsoft.AspNetCore.Components.DataAnnotations.Validation`](https://www.nuget.org/packages/Microsoft.AspNetCore.Components.DataAnnotations.Validation) is a package that fills validation experience gaps using the component. The package is currently *experimental*.