Asp.net-Mvc

試圖繼承RegularExpressionAttribute,不再驗證

  • February 26, 2018

我正在嘗試繼承RegularExpressionAttribute以通過驗證 SSN 來提高可重用性。

我有以下模型:

public class FooModel
{
   [RegularExpression(@"^(?!000)(?!666)(?!9[0-9][0-9])\d{3}[- ]?(?!00)\d{2}[- ]?(?!0000)\d{4}$", ErrorMessage = "The SSN you entered is invalid. If you do not have this number please leave the field blank")]
   public string Ssn { get; set; }
}

這將在客戶端和伺服器上正確驗證。我想將冗長的正則表達式封裝到它自己的驗證屬性中,如下所示:

public class SsnAttribute : RegularExpressionAttribute
{
   public SsnAttribute() : base(@"^(?!000)(?!666)(?!9[0-9][0-9])\d{3}[- ]?(?!00)\d{2}[- ]?(?!0000)\d{4}$")
   {
       ErrorMessage = "SSN is invalid";
   }
}

然後我改變了我的FooModel喜歡:

public class FooModel
{
   [Ssn(ErrorMessage = "The SSN you entered is invalid. If you do not have this number please leave the field blank")]
   public string Ssn { get; set; }
}

現在驗證不會在客戶端呈現不顯眼的數據屬性。我不太確定為什麼,因為這似乎兩者本質上應該是同一回事。

有什麼建議麼?

在您Application_Start添加以下行以將適配器關聯到您的自定義屬性,該屬性將負責發出客戶端驗證屬性:

DataAnnotationsModelValidatorProvider.RegisterAdapter(
   typeof(SsnAttribute), 
   typeof(RegularExpressionAttributeAdapter)
);

你需要這個的原因RegularExpressionAttribute是實現的方式。它沒有實現IClientValidatable介面,而是有一個RegularExpressionAttributeAdapter與之關聯的介面。

在您的情況下,您有一個派生自的自定義屬性,RegularExpressionAttribute但您的屬性沒有實現IClientValidatable介面以使客戶端驗證正常工作,也沒有與之關聯的屬性適配器(與其父類相反)。因此,您SsnAttribute應該IClientValidatable按照我之前的回答中的建議實現介面或關聯適配器。

就個人而言,我認為實現這個自定義驗證屬性沒有多大意義。在這種情況下,一個常數可能就足夠了:

public const string Ssn = @"^(?!000)(?!666)(?!9[0-9][0-9])\d{3}[- ]?(?!00)\d{2}[- ]?(?!0000)\d{4}$", ErrorMessage = "The SSN you entered is invalid. If you do not have this number please leave the field blank";

進而:

public class FooModel
{
   [RegularExpression(Ssn, ErrorMessage = "The SSN you entered is invalid. If you do not have this number please leave the field blank")]
   public string Ssn { get; set; }
}

看起來很可讀。

引用自:https://stackoverflow.com/questions/18666812