# ASP.Net MVC 服務端資料驗證
### 建立範例 Model
```csharp=
public class Staff
{
[Required, StringLength(10, MinimumLength = 1)]
public string Name { get; set; }
[Range(0, 100, ErrorMessage = "數值需介於0到100之間")]
public int Number { get; set; };
[EmailAddress]
public string Email { get; set; }
[Phone]
public string Phone { get; set; }
}
```
#### 驗證說明
* **Required:** 欄位資料為必填項目
* **Range:** 欄位數值範圍區間
* **EmailAddress:** 驗證 Email 格式
* **Phone:** 驗證手機號碼
* **ErrorMessage:** 自定義錯誤訊息
### 建立 Controller 及 Action
```csharp=
public class DemoController : Controller
{
// GET: Demo
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Staff staff)
{
if(ModelState.IsValid)
{
// do something if valid
}
return View(staff);
}
}
```
新增一組 Index Action 加上 **[HttpPost]** 屬性作為頁面表單 Post 使用。
### 建立 Form 表單
```csharp=
<form method="post">
<div class="form-group">
<label class="control-label">Name</label>
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
<div class="form-group">
<label class="control-label">Number</label>
@Html.EditorFor(model => model.Number, new { htmlAttributes = new { @class = "form-control", @Value = 0 } })
@Html.ValidationMessageFor(model => model.Number, "", new { @class = "text-danger" })
</div>
<div class="form-group">
<label class="control-label">Email</label>
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
</div>
<div class="form-group">
<label class="control-label">Phone</label>
@Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
</div>
<button class="btn btn-success mt-2">Submit</button>
</form>
```
### 結果顯示
* 表單 Submit 後頁面呈現驗證結果

* 姓名欄位字串長度驗證結果

### Remote 遠端驗證
#### 在 Staff 模型中新增 Unigue 屬性,並新增 [Remote] 標籤
```csharp=
[Remote("CheckExist", "Demo", HttpMethod = "POST", ErrorMessage = "It's Exist")]
public string Unique { get; set; }
```
#### Remote 參數說明
* Remote(Action, Controller, [HttpMethod], [ErrorMessage])
* 前兩個參數指定對應的 Action 及 Controller,後者可選填 Http 方法及錯誤訊息。
#### Controller 新增 CheckExist Action
```csharp=
[HttpPost]
public ActionResult CheckExist(string Unique)
{
List<string> exist = new List<string>{"A", "B"};
return Json(exist.Contains(Unique));
}
```
* 範例的 Controller 驗證 Unique 是否包含在 exist List 中
#### 開啟 Client 端驗證
因為 Remote 屬性是透過 jQuery 送出 Ajax 來進行遠端驗證,所以需要 Client 驗證功能開啟。
* Web.config,ClientValidationEnabled 及 UnobtrusiveJavaScriptEnabled 改為 True
```xml=
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
```
* 引入 jquery.validate.min.js、jquery.validate.unobtrusive.min.js
```csharp=
//因 BundleConfig.cs 已有設定,所以直接用 Scripts.Render 引入
@Scripts.Render("~/bundles/jqueryval")
```
### 結語
驗證模式真的太多種了,未來有機會實作驗證,再來補充。
> 成功的秘訣,在永不改變既定的目的。——盧梭
###### tags: `ASP.NET` `MVC`