在ASP.NET Core 2.1或更高版本中创建自定义的RequiredIf
验证器,可以通过实现IClientModelValidator
接口和IValidationAttribute
接口来完成。以下是一个详细的步骤和示例代码:
[Required]
)和自定义验证器来实现的。RequiredIf
验证器。例如,如果一个字段是“国家”,另一个字段是“邮政编码”,则只有在“国家”为特定值时,“邮政编码”才必须填写。using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
public class RequiredIfAttribute : ValidationAttribute, IClientModelValidator
{
private readonly string _dependentProperty;
private readonly object _targetValue;
public RequiredIfAttribute(string dependentProperty, object targetValue)
{
_dependentProperty = dependentProperty;
_targetValue = targetValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var instance = validationContext.ObjectInstance;
var type = instance.GetType();
var property = type.GetProperty(_dependentProperty);
if (property == null)
{
return new ValidationResult($"Unknown property: {_dependentProperty}");
}
var dependentValue = property.GetValue(instance, null);
if (dependentValue != null && dependentValue.Equals(_targetValue))
{
if (value == null || string.IsNullOrWhiteSpace(value.ToString()))
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
return ValidationResult.Success;
}
public void AddValidation(ClientModelValidationContext context)
{
MergeAttribute(context.Attributes, "data-val", "true");
MergeAttribute(context.Attributes, $"data-val-requiredif", ErrorMessage);
MergeAttribute(context.Attributes, $"data-val-requiredif-dependentproperty", _dependentProperty);
MergeAttribute(context.Attributes, $"data-val-requiredif-targetvalue", _targetValue?.ToString());
}
private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
}
public class MyModel
{
[RequiredIf("Country", "USA")]
public string ZipCode { get; set; }
public string Country { get; set; }
}
为了使客户端验证生效,需要添加相应的JavaScript代码:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.12/jquery.validate.unobtrusive.min.js"></script>
<script>
$.validator.addMethod("requiredif", function (value, element, params) {
var dependentProperty = params.dependentproperty;
var targetValue = params.targetvalue;
var dependentValue = $(`#${dependentProperty}`).val();
if (dependentValue === targetValue) {
return value !== "";
}
return true;
});
$.validator.unobtrusive.adapters.addBool("requiredif", ["dependentproperty", "targetvalue"]);
</script>
通过以上步骤和示例代码,您可以在ASP.NET Core中成功创建并使用自定义的RequiredIf
验证器。
领取专属 10元无门槛券
手把手带您无忧上云