model validation我需要RequiredIfNull
属性。
如何添加条件必需属性。条件取决于另一个财产。如果该属性值为null,那么这不应该是。
类似的东西:
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; }
}
答案 0 :(得分:2)
您需要自定义验证属性。例如:
<input type="number" id="myNumber" value="253">
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
然后在你的模型中:
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;
}
}
如果您还需要添加客户端验证,事情会变得更复杂。