2016-04-01 34 views
0

我有兩個自定義驗證來執行模型驗證。第一個是我用來查看字符串「<」和「>」中是否有字符的控件,第二個是查看兩個日期是否連續。ASP.NET MVC中的自定義驗證不起作用

尖括號驗證

public class AngleBracketsValidator : ValidationAttribute 
{  
    public override Boolean IsValid(Object value) 
    { 


     Boolean isValid = true; 
     if (value != null && (value.ToString().Contains('<') || value.ToString().Contains('>'))) 
     { 
      isValid = false; 
     } 

     return isValid; 
    } 
} 

日期驗證

public class CustomDateCompareValidator : ValidationAttribute 
{ 
    public String PropertyDateStartToCompare { get; set; } 

    public String PropertyDateEndToCompare { get; set; } 

    public CustomDateCompareValidator(string propertyDateStartToCompare, string propertyDateEndToCompare) 
    { 
     PropertyDateStartToCompare = propertyDateStartToCompare; 
     PropertyDateEndToCompare = propertyDateEndToCompare; 
    } 

    public override Boolean IsValid(Object value) 
    { 
     Type objectType = value.GetType(); 
     PropertyInfo[] neededProperties = 
      objectType.GetProperties() 
      .Where(propertyInfo => propertyInfo.Name == PropertyDateStartToCompare || propertyInfo.Name == PropertyDateEndToCompare) 
      .ToArray(); 

     if (neededProperties.Count() != 2) 
     { 
      throw new ApplicationException("CustomDateCompareValidator error on " + objectType.Name); 
     } 

     Boolean isValid = true; 
     if (Convert.ToDateTime(neededProperties[0].GetValue(value, null)) != Convert.ToDateTime("01/01/0001") && Convert.ToDateTime(neededProperties[1].GetValue(value, null)) != Convert.ToDateTime("01/01/0001")) 
     { 
      if (Convert.ToDateTime(neededProperties[0].GetValue(value, null)) > Convert.ToDateTime(neededProperties[1].GetValue(value, null))) 
      { 
       isValid = false; 
      } 
     }  
     return isValid; 
    } 
} 

模型:

[Serializable] 
[CustomDateCompareValidator("DtStart", "DtEnd", ErrorMessage = "the start date is greater than that of the end.")] 
public class ProjModel 
{ 
    [Display(Name = "Codice:")] 
    [AllowHtml] 
    [AngleBracketsValidator(ErrorMessage = "Code can not contain angle bracket.")] 
    public string Code { get; set; } 

    [Display(Name = "Date Start:")] 
    public DateTime? DtStart { get; set; } 

    [Display(Name = "Date End:")] 
    public DateTime? DtEnd { get; set; } 

} 

執行已知的測試,所述第一確認器,該角撐架的被顯示,而第二,日期,顯示。但是,如果我在隊列中發佈公平值,通過尖括號的驗證,日期驗證器查看將執行錯誤消息。 一些想法,使其正常工作?

+1

請換個問題。很難理解什麼是不起作用的。 – Mats

+0

對不起,我的英語不好......問題是我不能同時顯示兩個驗證器。 –

+0

你不應用你的'CustomDateCompareValidator'類。你將它應用到模型中的一個屬性 - 比如說'DtEnd',並且你提供其他屬性('DtStart')來比較它。建議您使用[萬無一失](http://foolproof.codeplex.com/)'[GreaterThan]'或類似的驗證屬性,這也將爲您提供客戶端驗證。 –

回答

0

「這不被支持,如果任何屬性級別驗證失敗,則不執行級別級別驗證」。 看原版entry