blazor 进行表单校验

Blazor 表单校验

使用 EditForm

ASP.NET Core Blazor 输入组件 | Microsoft Learn

1
2
3
4
5
6
7
8
9
10
11
12
13
<EditForm EditContext="editContext" OnValidSubmit="Submit" FormName="newCategoryForm">
<div class="form-group">
<label for="CatName">类别名称</label>
<InputText class="text-input" id="CatName" @bind-Value="_newCategory.CatName"/>
<ValidationMessage class="text-orange-300" For="() => _newCategory.CatName"></ValidationMessage>
</div>
<div class="form-group">
<label for="CatColor">类别颜色</label>
<InputText id="CatColor" type="color" @bind-Value="_newCategory.CatColor"/>
<ValidationMessage class="text-orange-300" For="() => _newCategory.CatColor"></ValidationMessage>
</div>
<button class="my-btn" type="submit">提交</button>
</EditForm>

其中:

  • FormName 填写一个每个表单不重复的名称
  • _newCategory 是后台绑定的一个模型,具有 CatNameCatColor 属性。

后天

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class NewCategory
{
public string CatName { get; set; }
public string CatColor { get; set; }
}

// 需要标注 [SupplyParameterFromForm]
[SupplyParameterFromForm] private NewCategory _newCategory { get; set; } = new NewCategory();

// 用于检查
private static readonly Regex _colorRegex = new("^#[0-9a-fA-F]{6}$", RegexOptions.Compiled);

// 使用 EditContext 和 ValidationMessageStore
private EditContext? editContext;
private ValidationMessageStore? messageStore;


protected override void OnInitialized()
{
_newCategory ??= new();
editContext = new(_newCategory);
editContext.OnValidationRequested += (sender, args) =>
{
messageStore?.Clear();
// 添加到 messageStore 后,就会在前端对应的 ValidationMessage 内显示。
if (string.IsNullOrEmpty(_newCategory.CatName))
{
messageStore?.Add(editContext.Field("CatName"), "类别名称不能为空。");
}

if (string.IsNullOrEmpty(_newCategory.CatColor) || !_colorRegex.IsMatch(_newCategory.CatColor))
{
messageStore?.Add(editContext.Field("CatColor"), "类别颜色格式不正确。");
}
};
messageStore = new(editContext);
}

使用手动检查

对于简单的字符串检查:

ASP.NET Core Blazor 数据绑定 | Microsoft Learn

1
2
3
4
5
6
7
8
9
<input class="text-input"
type="text"
@bind:get="chargeDate"
@bind:set="ValidateDateInput"
@bind:event="oninput" />
@if (!isDateValid)
{
<div class="text-orange-300">日期格式不正确</div>
}

chargeDate 是一个字符串。

使用 @bind:get/@bind:set 修饰符,既能通过 @bind:set 控制 chargeDate 的基础值,又能通过 @bind:getinputValue 的值绑定到元素的值。

@bind:event="oninput" 会在输入变更后立即触发校验。

1
2
3
4
5
6
7
8
9
10
11
12
private string chargeDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
private bool isDateValid = true;

private void ValidateDateInput(string obj)
{
// 由于不再是直接 @bind,需要手动更新 chargeDate 的值
chargeDate = obj;
// 更新布尔变量
isDateValid = DateTime.TryParse(obj, out DateTime date);
// 通知界面状态变化
StateHasChanged();
}

blazor 进行表单校验
https://taylorandtony.github.io/2025/02/02/blazor-进行表单校验/
作者
TaylorAndTony
发布于
2025年2月2日
许可协议