ASP.NET Core 控件的条件验证可以通过以下解决方法进行:
public class MyViewModel
{
[Required]
public string Name { get; set; }
[Required]
[Range(18, 99)]
public int Age { get; set; }
[RequiredIf("Age", 21)]
public string Drink { get; set; }
}
public class RequiredIfAttribute : ValidationAttribute, IClientModelValidator
{
private readonly string _dependentProperty;
private readonly object _dependentValue;
public RequiredIfAttribute(string dependentProperty, object dependentValue)
{
_dependentProperty = dependentProperty;
_dependentValue = dependentValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var dependentPropertyValue = validationContext.ObjectInstance.GetType()
.GetProperty(_dependentProperty)?.GetValue(validationContext.ObjectInstance, null);
if (dependentPropertyValue != null && dependentPropertyValue.ToString() == _dependentValue.ToString())
{
if (value == null || string.IsNullOrEmpty(value.ToString()))
{
return new ValidationResult(ErrorMessage);
}
}
return ValidationResult.Success;
}
public void AddValidation(ClientModelValidationContext context)
{
var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
context.Attributes.Add("data-val", "true");
context.Attributes.Add("data-val-requiredif", errorMessage);
context.Attributes.Add("data-val-requiredif-dependentproperty", _dependentProperty);
context.Attributes.Add("data-val-requiredif-dependentvalue", _dependentValue.ToString());
}
}
在视图中,使用控件绑定视图模型的属性,并指定相应的 HTML 属性。
public class MyViewModel
{
[Required]
public string Name { get; set; }
[Required]
[Range(18, 99)]
public int Age { get; set; }
[RequiredIf("Age", 21)]
public string Drink { get; set; }
}
在视图中,引入相应的 JavaScript 文件,并编写脚本来实现条件验证。
@section Scripts