在 Model 類別屬性標註 `[MaxLength(16, ErrorMessage = "最大長度 16")]`,但對應的 `` **未產生** `data-val-length`、`data-val-length-max` 等 Unobtrusive 驗證屬性,前端驗證不生效。
using System.ComponentModel.DataAnnotations;
public class ProductViewModel
{
// ✅ 正確:同時產生資料庫欄位長度 + 前後端驗證
[StringLength(16, ErrorMessage = "最大長度 16 個字元")]
public string Name { get; set; }
// ❌ 錯誤:僅影響 EF Migration,無客戶端驗證
// [MaxLength(16, ErrorMessage = "最大長度 16")]
// public string Name { get; set; }
}
[StringLength(
maximumLength: 50, // 最大長度 (資料庫 nvarchar(50))
MinimumLength = 2, // 最小長度 (可選)
ErrorMessage = "長度需 2-50 字元" // 錯誤訊息
)]
public string Description { get; set; }
產生的 HTML 屬性:
<input data-val="true"
data-val-length="長度需 2-50 字元"
data-val-length-max="50"
data-val-length-min="2"
name="Description" />
**不需同時標註**。`StringLength` 會同時作為 EF 欄位長度依據 (Code First Migration 產生 `nvarchar(50)`)。若極少數情況需分離 (如資料庫 `nvarchar(100)` 但 UI 限制 50):**以 StringLength 為主,EF 以 Fluent API 覆寫**:
// Model
[StringLength(50)]
public string Name { get; set; }
// DbContext OnModelCreating
modelBuilder.Entity()
.Property(p => p.Name)
.HasMaxLength(100); // 資料庫實際允許 100,UI 驗證 50
| 屬性 | 命名空間 | 客戶端驗證 | EF 欄位長度 | 備註 |
|---|---|---|---|---|
| `StringLength` | DataAnnotations | ✅ | ✅ | **首選** |
| `MaxLength` | DataAnnotations | ❌ | ✅ | 僅 EF Schema |
| `MinLength` | DataAnnotations | ✅ (MVC 5.1+) | ❌ | 需搭配 StringLength/MaxLength |
| `Required` | DataAnnotations | ✅ | ✅ (非 null) | 非空驗證 |
| `RegularExpression` | DataAnnotations | ✅ | ❌ | Regex 模式驗證 |
ASP.NET MVC 模型驗證**請統一使用 `StringLength`** 取代 `MaxLength`,一行代碼同時解決資料庫 Schema 定義與前後端長度驗證。這是框架設計的慣例,避免踩坑請記住:**驗證用 StringLength,EF 映射也用 StringLength (或 Fluent API 覆寫)**。