本篇文章同步發表於 個人部落格 Jim's Blog
今天來介紹表單驗證該怎麼做,透過 Blazor 內建表單元件,來做到對欄位的驗證
在 C# 內的 System.ComponentModel.DataAnnotations 命名空間有微軟提供的驗證屬性,這邊介紹幾個比較常用的屬性
如果在 DataAnnotations 找不到想要的可以自己實作驗證的 Attribute
自訂驗證 Attribute 要繼承 ValidationAttribute 並且覆寫 IsVaiid 方法,例如我要做一個規定欄位只能是偶數的寫起來像這樣
public class EvenOnlyAttribute : ValidationAttribute
{
    public EvenOnlyAttribute(int value)
    {
        Value = value;
    }
    public int Value { get; }
    protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
    {
        return (int)value! % 2 == 0 ? new ValidationResult("數值不是偶數") : ValidationResult.Success;
    }
}
然後再想要套用資料檢核的欄位使用就可以了
[EvenOnly]
public int Value {get;set;}
處理完有什麼欄位需要驗證後,接下來看到與 HTML 表單該怎麼做繫結,這部分來實作一個簡單的登入表單
class LoginModel
{
    [Required (ErrorMessage = "使用者名稱為必填")]
    public string Username { get; set; }
    [Required(ErrorMessage = "密碼為必填")]
    [RegularExpression(@"^(?=.*\d)(?=.*[a-zA-Z])(?=.*\W).{6,30}$",ErrorMessage = "須為複雜密碼")]
    public string Password { get; set; }
}
@page "/Login"
@using System.ComponentModel.DataAnnotations
<EditForm Model="@loginModel" OnValidSubmit="@HandleValidSubmit" class="form-signin w-100 m-auto">
    <DataAnnotationsValidator />
    <ValidationSummary />
    <div class="form-floating">
        <InputText @bind-Value="loginModel.Username" class="form-control" id="username" />
        <label for="username">使用者名稱</label>
    </div>
    <div class="form-floating">
        <InputText type="password" @bind-Value="loginModel.Password" class="form-control" id="password" />
        <label for="password">密碼</label>
    </div>
    <button type="submit" class="w-100 btn btn-lg btn-primary">登入</button>
</EditForm>
<style>
    .form-signin {
        max-width: 330px;
        padding: 15px;
    }
</style>
@code {
    private LoginModel loginModel = new();
    private void HandleValidSubmit()
    {
    }
    class LoginModel
    {
        [Required (ErrorMessage = "使用者名稱為必填")]
        public string Username { get; set; }
        [Required(ErrorMessage = "密碼為必填")]
        [RegularExpression(@"^(?=.*\d)(?=.*[a-zA-Z])(?=.*\W).{6,30}$",ErrorMessage = "須為複雜密碼")]
        public string Password { get; set; }
    }
}
都有填寫但是密碼欄位未符合規格
表單送出時有三個 Callback 供使用
EditContext.Validate 來得知表單是否驗證通過到這邊基本的表單使用介紹的差不多了,今天認識了預設的元件 EditForm,明天介紹其他適用於表單的內建元件