0

在我們的數據庫中,我們有幾個代碼表,我們用於參照完整性(例如emailTypes,phoneTypes,countryCodes,stateCodes)。在我們的應用程序中,我們加載並緩存這些表到通用列表中現在,應用程序爲每個列表定製ValidationAttributes,以查看提交的值是否在硬編碼值列表中。我相信這可以用一個新的自定義驗證屬性來重寫,該驗證屬性接受一個通用列表,該屬性用於搜索該值的值和數據類型,如果值存在於列表中,則返回有效值。ValidationAttribute驗證值是在屬性上的一個通用列表

首先,我想知道是否我甚至可以使用編譯時間列表在運行時在自定義驗證屬性中填充。

如果是這樣,有沒有人想出了一個很好的解決方案呢?如果沒有,是否有一項很好的工作?

如果您包含 IClientValidatable進行js驗證,我將包含獎勵積分(不是該計算器具有獎勵積分)。

回答

0

您可以使用下面的代碼來實現中央驗證邏輯

public abstract class GenericValidationAttribute:ValidationAttribute 
{ 
    protected GenericValidationAttribute(DataValidationType dataValidationType) 
    { 
     ValidationType = dataValidationType; 
    } 

    protected DataValidationType ValidationType { get; set; } 

    public override bool IsValid(object value) 
    { 
     switch (ValidationType) 
     { 
      case DataValidationType.Email: 
       //Check if the value is in the built-in emails 
       break; 
      case DataValidationType.Phone: 
       //Check if the value is in the phone list 
       break; 
     } 

     return base.IsValid(value); 
    } 
} 

public class EmailValidationAttribute : GenericValidationAttribute 
{ 
    public EmailValidationAttribute() : base(DataValidationType.Email) 
    {} 

} 


public enum DataValidationType 
{ 
    Email, 
    Phone, 
    Country, 
    State 
} 

只要把驗證邏輯到通用驗證屬性,並有其他特定的驗證類從它繼承。

乾杯。

+0

雖然此解決方案確實將驗證本地化到單個位置,但它不會回答我的問題,只要驗證客戶端在列表中傳遞,以及要搜索的屬性和搜索的數據類型。 我正在尋找一種解決方案,接受這樣的事情,以便我不必爲每個列表重新編碼驗證。 [GenericListValidation(ListToVerify,PropertyToSearch,DataType)] 也許這是不可能的。 – user1041169

0

我做了一些假設。

  1. 集合在一個靜態類的靜態屬性
  2. 集合自IList

首先繼承你需要自定義屬性

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] 
public class ListCheckAttribute : ValidationAttribute 
{ 
    // The name of the class that holds the collection 
    public Type ContainerType { get; private set; } 
    // The name of the property holding the list 
    public string PropertyName { get; private set; } 

    public ListCheckAttribute(Type ContainerType, String PropertyName) 
    { 
     this.ContainerType = ContainerType; 
     this.PropertyName = PropertyName; 
    } 

    public override bool IsValid(object value) 
    { 
     var property = ContainerType.GetProperty(this.PropertyName); 
     var val = property.GetMethod.Invoke(null, null); 
     var list = (IList)val; 
     return list.Contains(value); 
    } 
} 

public class MyClass 
{ 
    [ListCheck(typeof(CollectionClass), "Collection")] 
    public int NumberToValidate { get; set; } 

    public MyClass() 
    { 
     NumberToValidate = 4; 
    } 
} 

現在,當確認處理程序調用的isValid它得到來自列表 的屬性並將它們投射到IList,以便可以完成一個包含。對於類,他們所要做的就是實現IEquatable並實現Equals方法,它們也可以工作。

相關問題