2012-03-05 26 views
5

Tôi muốn sử dụng ComponentModel DataAnnotations xác thực rằng ít nhất một trong hai thuộc tính có một giá trị. Mô hình của tôi trông như thế này:Hoặc là yêu cầu xác nhận

public class FooModel { 
    public string Bar1 { get; set; } 
    public int Bar2 { get; set; } 
} 

Về cơ bản, Tôi muốn xác nhận FooModel để một trong hai bar1 hoặc Bar2 cần. Nói cách khác, bạn có thể nhập một, hoặc khác, hoặc cả hai, nhưng bạn không thể chỉ để lại cho họ cả hai sản phẩm nào.

Tôi muốn điều này làm việc cả cho xác thực phía máy khách và không phô trương.


EDIT: Đây có thể là một possible duplicate, as this looks similar to what I'm looking to do

+2

Đúng validator tùy chỉnh là bạn của bạn ở đây. – veblock

+1

Có trình xác thực tùy chỉnh được gọi là RequiredIf có thể giải quyết được sự cố của bạn. – Joe

+0

@JoeTuskan, bạn nói đúng, tôi đã tìm thấy [bài đăng trên blog này] (http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc -3.aspx) về hướng dẫn của bạn và nó giải quyết vấn đề của tôi. Nếu bạn muốn nhập câu trả lời để tôi có thể cung cấp cho bạn tín dụng, điều đó là tốt cho tôi. Nếu không, hãy +1 của tôi. –

Trả lời

4

Bạn sẽ cần phải mở rộng các lớp ValidationAttribute và hơn đi xe phương pháp IsValid, và thực hiện các IClientValidatable nếu bạn muốn bơm tùy chỉnh hoạt Javascript để thực hiện xác nhận. một cái gì đó như dưới đây.

[AttributeUsage(AttributeTargets.Property)] 
    public sealed class AtLeastOneOrTwoParamsHasValue : ValidationAttribute, IClientValidatable 
    { 
     protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
     { 
      var param1 = validationContext.ObjectInstance.GetType().GetProperty("Param1").GetValue(value, null); 
      //var param2 = validationContext.ObjectInstance.GetType().GetProperty("Param2").GetValue(value, null); 

      //DO Compare logic here. 

      if (!string.IsNullOrEmpty(Convert.ToString(param1))) 
      { 
       return ValidationResult.Success; 
      } 


      return new ValidationResult("Some Error"); 
     } 

     public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
     { 
      //Do custom client side validation hook up 

      yield return new ModelClientValidationRule 
      { 
       ErrorMessage = FormatErrorMessage(metadata.DisplayName), 
       ValidationType = "validParam" 
      }; 
     } 
    } 

Cách sử dụng:

[AtLeastOneOrTwoParamsHasValue(ErrorMessage="Atleast one param must be specified.")] 
Các vấn đề liên quan