あなたはカスタム検証属性を必要としています。たとえば:
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; }
}
物事はより複雑になります。