Blazor 表单校验
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 是后台绑定的一个模型,具有 CatName 和 CatColor 属性。
后天
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] private NewCategory _newCategory { get; set; } = new NewCategory();
private static readonly Regex _colorRegex = new("^#[0-9a-fA-F]{6}$", RegexOptions.Compiled);
private EditContext? editContext; private ValidationMessageStore? messageStore;
protected override void OnInitialized() { _newCategory ??= new(); editContext = new(_newCategory); editContext.OnValidationRequested += (sender, args) => { messageStore?.Clear(); 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:get 将 inputValue 的值绑定到元素的值。
@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) { chargeDate = obj; isDateValid = DateTime.TryParse(obj, out DateTime date); StateHasChanged(); }
|