這邊來介紹模型延伸-Model驗證,主要是檢查表單欄位值是否合法,以免跑到後面資料會有問題的一道防線,例如EMAIL的格式、欄位是否必填、至少填幾個字元、是否為數字等等...
簡單為Scott類別加幾個屬性如下:
public class Scott
{
[Display(Name = "號碼")]
public int ID { get; set; }
[Required(ErrorMessage ="名字不可為空")]
public string Name { get; set; }
[Display(Name = "年齡")]
public int Age { get; set; }
[Display(Name = "地址")]
public string Address { get; set; }
}
接著,我們在上一章的controller新增一個名為Create的Action,右鍵->新增檢視->Create,接收前端Scott類別的物件,並在Create中加入ModelState.IsValid這個判斷式,才會進行Model驗證(後端做)
[HttpPost]
public IActionResult Create(Scott scottObj)
{
if (ModelState.IsValid)
{
//做存入資料庫的動作
.......
//導回首頁
return RedirectToAction(nameof(Index));
}
return View(scottObj);
}
接著來撰寫前端頁面,使用剛剛做好的Create.cshtml
<form asp-action="create">
<div asp-validation-summary="All"></div>
<div>
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name" data-valmsg-replace="false">*</span>
</div>
<div>
<label asp-for="Age"></label>
<input asp-for="Age" />
<span asp-validation-for="Age" data-valmsg-replace="false">*</span>
</div>
<div>
<label asp-for="Address"></label>
<input asp-for="Address" />
<span asp-validation-for="Address" data-valmsg-replace="false">*</span>
</div>
<div>
<input type="submit" value="Save" />
</div>
</form>
接著就執行Debug mode,開啟我們剛剛的頁面,甚麼都不填入,按下Save按鈕,會發現在ModelState.IsValid回傳false,後端Model驗證成功!
自定義驗證
如果以上簡單的屬性無法滿足你的需求的話,當然也有為欄位套上自定義邏輯的Model驗證,但必須有前置準備。
public class CheckValidAge:ValidationAttribute
{
//ctor
public CheckValidAge()
{
ErrorMessage = "年齡不可超過50歲";
}
public override bool IsValid(object value)
{
if (value==null)
{
return true;
}
int age = (int)value;
if (age > 50)
{
return false;
}
else
{
return true;
}
}
}
最後我們就可在Scott類別中的Age掛上[CheckValidAge]即可完成自定義驗證!
public class Scott
{
[Display(Name = "號碼")]
public int ID { get; set; }
[Required(ErrorMessage ="名字不可為空")]
public string Name { get; set; }
[Display(Name = "年齡")]
[CheckValidAge]
public int Age { get; set; }
[Display(Name = "地址")]
public string Address { get; set; }
}
參考資料
https://docs.microsoft.com/zh-tw/aspnet/core/mvc/models/validation?view=aspnetcore-3.1