Skip to content

Commit 860d795

Browse files
authored
Blazor custom validation class attributes (#19909)
1 parent 0ad6b19 commit 860d795

1 file changed

Lines changed: 27 additions & 1 deletion

File tree

aspnetcore/blazor/forms-validation.md

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ description: Learn how to use forms and field validation scenarios in Blazor.
55
monikerRange: '>= aspnetcore-3.1'
66
ms.author: riande
77
ms.custom: mvc
8-
ms.date: 08/18/2020
8+
ms.date: 09/17/2020
99
no-loc: ["ASP.NET Core Identity", cookie, Cookie, Blazor, "Blazor Server", "Blazor WebAssembly", "Identity", "Let's Encrypt", Razor, SignalR]
1010
uid: blazor/forms-validation
1111
---
@@ -1015,6 +1015,32 @@ private class CustomValidator : ValidationAttribute
10151015
> [!NOTE]
10161016
> <xref:System.ComponentModel.DataAnnotations.ValidationContext.GetService%2A?displayProperty=nameWithType> is `null`. Injecting services for validation in the `IsValid` method isn't supported.
10171017
1018+
::: moniker range=">= aspnetcore-5.0"
1019+
1020+
## Custom validation class attributes
1021+
1022+
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 <xref:Microsoft.AspNetCore.Components.Forms.EditContext> instance:
1023+
1024+
```csharp
1025+
var editContext = new EditContext(model);
1026+
editContext.SetFieldCssClassProvider(new MyFieldClassProvider());
1027+
1028+
...
1029+
1030+
private class MyFieldClassProvider : FieldCssClassProvider
1031+
{
1032+
public override string GetFieldCssClass(EditContext editContext,
1033+
in FieldIdentifier fieldIdentifier)
1034+
{
1035+
var isValid = !editContext.GetValidationMessages(fieldIdentifier).Any();
1036+
1037+
return isValid ? "good field" : "bad field";
1038+
}
1039+
}
1040+
```
1041+
1042+
::: moniker-end
1043+
10181044
### Blazor data annotations validation package
10191045

10201046
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 <xref:Microsoft.AspNetCore.Components.Forms.DataAnnotationsValidator> component. The package is currently *experimental*.

0 commit comments

Comments
 (0)