首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET MVC MaxLength 屬性驗證失效:改用 StringLength 解決

     編輯:ASP.NET 基礎

問題現象

在 Model 類別屬性標註 `[MaxLength(16, ErrorMessage = "最大長度 16")]`,但對應的 `` **未產生** `data-val-length`、`data-val-length-max` 等 Unobtrusive 驗證屬性,前端驗證不生效。

根本原因

  • `System.ComponentModel.DataAnnotations.MaxLengthAttribute` **主要用於 EF Code First 定義資料庫欄位長度** (`nvarchar(16)`)。
  • ASP.NET MVC **預設 ModelValidatorProvider 不處理 `MaxLength` 產生客戶端驗證規則**。
  • `StringLengthAttribute` 同時支援 **資料庫 Schema 定義** 與 **客戶端/伺服端驗證**。

解決方案:直接替換為 StringLength

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 完整參數

[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" />

進階:同時需要 MaxLength (EF) + StringLength (驗證)?

**不需同時標註**。`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 覆寫)**。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved