ASP.NET Core MVC 核心設計遵循 **DRY (Don't Repeat Yourself)**:在模型類別單一位置以屬性聲明驗證規則,控制器、視圖、用戶端腳本自動套用,減少重複代碼與錯誤。
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Movie
{
public int Id { get; set; }
[Required(ErrorMessage = "片名不可為空")]
[StringLength(60, MinimumLength = 3, ErrorMessage = "片名長度需 3-60 字元")]
[Display(Name = "電影片名")]
public string Title { get; set; }
[Display(Name = "上映日期")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime ReleaseDate { get; set; }
[Required]
[RegularExpression(@"^[A-Z]+[a-zA-Z\s'*\-]*$", ErrorMessage = "類別僅限字母、空格、單引號、連字號")]
[StringLength(30)]
[Display(Name = "電影類別")]
public string Genre { get; set; }
[Range(1, 100, ErrorMessage = "價格需在 1 到 100 之間")]
[DataType(DataType.Currency)]
[Column(TypeName = "decimal(18,2)")]
[Display(Name = "票價")]
public decimal Price { get; set; }
[RegularExpression(@"^[A-Z]+[a-zA-Z\s'*\-]*$")]
[StringLength(5)]
[Display(Name = "分級")]
public string Rating { get; set; }
}
| 屬性 | 用途 | 關鍵參數 |
|---|---|---|
| [Required] | 必填 | ErrorMessage, AllowEmptyStrings |
| [StringLength] | 字串長度 | MaximumLength, MinimumLength |
| [Range] | 數值/日期範圍 | min, max, ErrorMessage |
| [RegularExpression] | Regex 模式比對 | Pattern, ErrorMessage |
| [EmailAddress] | Email 格式 | - |
| [Phone] | 電話格式 | - |
| [Url] | URL 格式 | - |
| [Compare] | 比對另一屬性 (如確認密碼) | OtherProperty |
| [Remote] | 遠端 AJAX 驗證 (檢查帳號唯一) | Action, Controller, AdditionalFields |
| [CustomValidation] | 自訂靜態驗證方法 | Method, ValidatorType |
// Package Manager Console
Add-Migration DataAnnotations_UpdateSchema
Update-Database
// 產生的 Up() 內容範例
protected override void Up(MigrationBuilder mb)
{
mb.AlterColumn("Title", "Movies", maxLength: 60, nullable: false, oldClrType: typeof(string), oldNullable: true);
mb.AlterColumn("Genre", "Movies", maxLength: 30, nullable: false);
mb.AlterColumn("Rating", "Movies", maxLength: 5, nullable: true);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task Create([Bind("Id,Title,ReleaseDate,Genre,Price,Rating")] Movie movie)
{
if (ModelState.IsValid) // 執行所有屬性驗證
{
_context.Add(movie);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(movie); // 驗證失敗回傳 View,自動攜帶錯誤訊息
}
<form asp-action="Create" method="post">
<div class="form-group">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<!-- 其他欄位同理 -->
<button type="submit" class="btn btn-primary">建立</button>
</form>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
若伺服器文化特性使用逗號做小數點 (如 `de-DE`),`[Range(1,100)]` 驗證 `99.9` 會失敗。解決方案:
// Startup.cs / Program.cs
services.Configure(opts =>
{
var supported = new[] { new CultureInfo("en-US"), new CultureInfo("zh-TW") };
opts.DefaultRequestCulture = new RequestCulture("en-US"); // 強制用點號解析數字
opts.SupportedCultures = supported;
opts.SupportedUICultures = supported;
});
app.UseRequestLocalization();
或安裝 Microsoft.AspNetCore.Mvc.NewtonsoftJson 並設定 `JsonSerializerSettings.Culture = CultureInfo.InvariantCulture`。
public class PastDateAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext context)
{
if (value is DateTime dt && dt > DateTime.Today)
return new ValidationResult("日期不可晚於今天");
return ValidationResult.Success;
}
}
// 使用
[PastDate(ErrorMessage = "上映日期不可為未來")]
public DateTime ReleaseDate { get; set; }