2017-08-08 23 views
0

model validationにはRequiredIfNullの属性が必要です。 条件付き必須属性を追加する方法を教えてください。条件は別のプロパティに依存します。そのプロパティー値がnullの場合、これは無効にする必要があります。そのようなモデルの検証:RequireIfNull属性(ASP.NETコア)

何か:

public class MyModel 
{ 
    public int? prop1 { get; set; } 

    [ConditionalRequired(prop1)]  //if prop1 == null, then prop2 is required, otherwise MyModel is invalid 
    public int? prop2 { get; set; } 
} 

答えて

2

あなたはカスタム検証属性を必要としています。たとえば:

using System.ComponentModel.DataAnnotations; 
using System.Reflection; 

    [AttributeUsage(AttributeTargets.Property)] 
    public class RequiredIfNullAttribute : ValidationAttribute 
    { 
     private const string DefaultErrorMessageFormat = "The {0} field is required."; 

     public RequiredIfNullAttribute(string otherProperty) 
     { 
      if (otherProperty == null) 
      { 
       throw new ArgumentNullException(nameof(otherProperty)); 
      } 

      OtherProperty = otherProperty; 
      ErrorMessage = DefaultErrorMessageFormat; 
     } 

     public string OtherProperty { get; } 

     protected override ValidationResult IsValid(object value, 
      ValidationContext validationContext) 
     { 
      if (value == null) 
      { 
       var otherProperty = validationContext.ObjectInstance. 
        GetType().GetProperty(OtherProperty); 
       object otherPropertyValue = otherProperty.GetValue(
        validationContext.ObjectInstance, null); 

       if (otherPropertyValue == null) 
       { 
        return new ValidationResult(
         string.Format(ErrorMessageString, validationContext.DisplayName)); 
       } 
      } 

      return ValidationResult.Success; 
     } 
    } 

は、その後、あなたのモデルに:あなたは、クライアント側の検証を追加する必要がある場合

public class MyModel 
{ 
    public int? prop1 { get; set; } 

    [RequiredIfNull(nameof(prop1))] 
    public int? prop2 { get; set; } 
} 

物事はより複雑になります。

関連する問題