修改验证逻辑

This commit is contained in:
hello 2024-09-18 22:13:40 +08:00
parent 36c8b15620
commit 168a33b99b
2 changed files with 99 additions and 0 deletions

View File

@ -0,0 +1,23 @@
# Blazor 全球化与本地化
Blazor 应用程序可以通过使用 .NET Core 的全球化和本地化功能来支持多种语言和文化。本文将介绍如何在 Blazor 应用程序中实现全球化和本地化。
## Blazor WebAssembly
```xml
<PropertyGroup>
<BlazorWebAssemblyLoadAllGlobalizationData>true</BlazorWebAssemblyLoadAllGlobalizationData>
</PropertyGroup>
```
```shell
dotnet add package Microsoft.Extensions.Localization
```
## Blazor Server
```csharp
builder.Services.AddCustomLocalization();
```
```csharp
app.UseCustomLocalization();
```

View File

@ -0,0 +1,76 @@
# Blazor 表单验证
## 使用数据注解 DataAnnotations 验证
```csharp
public class Employee
{
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
}
```
```csharp
@page "/employee"
@using System.ComponentModel.DataAnnotations
@using Microsoft.AspNetCore.Components.Forms
<h3>Employee Form</h3>
<EditForm Model="@employee" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="form-group">
<label for="Name">Name</label>
<InputText id="Name" @bind-Value="employee.Name" class="form-control" />
<ValidationMessage For="@(() => employee.Name)" />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</EditForm>
@code {
private Employee employee = new Employee();
}
```
## 使用 FluentValidation 验证
```shell
dotnet add package Blazored.FluentValidation
```
```csharp
public class EmployeeValidator : AbstractValidator<Employee>
{
public EmployeeValidator()
{
RuleFor(x => x.Name).NotEmpty().WithMessage("Name is required");
}
}
```
```csharp
@page "/employee"
@using FluentValidation
@using FluentValidation.Results
<h3>Employee Form</h3>
<EditForm Model="@employee" OnValidSubmit="@HandleValidSubmit">
<FluentValidationValidator DisableAssemblyScanning="@true" />
<ValidationSummary />
<div class="form-group">
<label for="Name">Name</label>
<InputText id="Name" @bind-Value="employee.Name" class="form-control" />
<ValidationMessage For="@(() => employee.Name)" />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</EditForm>
```
## 自定义验证