2011-04-04 41 views
1

在我的註冊頁面我有陸地電話號碼和手機號碼字段。有條件的或在asp.net驗證mvc2

我需要確保用戶需要添加至少一個電話號碼,無論是陸線還是手機。

我該怎麼做?

感謝 ARNAB

回答

4

你可以寫一個自定義的驗證屬性,並用它裝點你的模型:

[AttributeUsage(AttributeTargets.Class)] 
public class AtLeastOnePhoneAttribute: ValidationAttribute 
{ 
    public override bool IsValid(object value) 
    { 
     var model = value as SomeViewModel; 
     if (model != null) 
     { 
      return !string.IsNullOrEmpty(model.Phone1) || 
        !string.IsNullOrEmpty(model.Phone2); 
     } 
     return false; 
    } 
} 

然後:

[AtLeastOnePhone(ErrorMessage = "Please enter at least one of the two phones")] 
public class SomeViewModel 
{ 
    public string Phone1 { get; set; } 
    public string Phone2 { get; set; } 
} 

對於您可能需要更高級的驗證場景看看FluentValidation.NETFoolproof

+0

的驗證工作,但錯誤信息沒有顯示時,需要對單個字段添加驗證,因爲在這種情況下,我將驗證註釋添加到類中,我需要額外做些什麼 – Arnab 2011-04-06 01:51:34

+0

@Arnab,驗證消息將與「ValidationSummary」助手一起顯示。因爲這是一個類級別驗證程序,所以它不與任何屬性關聯,因此添加到模型狀態的密鑰爲空。如果您想將其與某些字段相關聯,則需要使用其他框架,例如我在答案中鏈接的框架,因爲數據註釋不支持此框架。 – 2011-04-06 05:53:27

+0

驗證摘要在那裏,但不顯示。難道是因爲我在模型中使用註釋,而模型是在視圖中調用的viewmodel內部。 – Arnab 2011-04-08 18:13:32

1

並稱可以應用於單獨的屬性,而不是在類級重寫驗證方法的溶液...

創建以下自定義屬性。請注意構造函數中的「otherPropertyName」參數。這將允許您傳入其他屬性以用於驗證。

public class OneOrOtherRequiredAttribute: ValidationAttribute 
{ 
    public string OtherPropertyName { get; set; } 
    public OneOrOtherRequiredAttribute(string otherPropertyName) 
    { 
     OtherPropertyName = otherPropertyName; 
    } 

    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     var otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherPropertyName); 
     var otherValue = (string)otherPropertyInfo.GetValue(validationContext.ObjectInstance, null); 
     if (string.IsNullOrEmpty(otherValue) && string.IsNullOrEmpty((string)value)) 
     { 
      return new ValidationResult(this.ErrorMessage); //The error message passed into the Attribute's constructor 
     } 
     return null; 
    } 
} 

然後,您可以裝飾你的屬性,像這樣:(一定要在其他屬性的名稱通過與比較)

[OneOrOtherRequired("GroupNumber", ErrorMessage = "Either Group Number or Customer Number is required")] 
public string CustomerNumber { get; set; } 

[OneOrOtherRequired("CustomerNumber", ErrorMessage="Either Group Number or Customer Number is required")] 
public string GroupNumber { get; set; }