Blazor custom validation class attributes (#19909)
parent
0ad6b196d3
commit
860d795623
|
@ -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]
|
||||
> <xref:System.ComponentModel.DataAnnotations.ValidationContext.GetService%2A?displayProperty=nameWithType> 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 <xref:Microsoft.AspNetCore.Components.Forms.EditContext> 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 <xref:Microsoft.AspNetCore.Components.Forms.DataAnnotationsValidator> component. The package is currently *experimental*.
|
||||
|
|
Loading…
Reference in New Issue