我为输入类型编号设置了自定义验证器。我想将最小和最大长度都限制为16 ..我成功添加了自定义验证器,并在页面渲染时在输入字段上获取数据属性,但发现它没有验证字段。这是我的代码看起来像
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class MaxDigitValidator : ValidationAttribute, IClientValidatable
{
private int _Max, _Min;
public MaxDigitValidator(int max, int min, string errorMessage)
: base(errorMessage)
{
_Max = max;
_Min = min;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ValidationResult validationResult = ValidationResult.Success;
try
{
if (!IsValid(value))
{
validationResult = new ValidationResult(ErrorMessageString);
}
else
{
validationResult = new ValidationResult("An error occurred while validating the property. OtherProperty is not of type DateTime");
}
}
catch (Exception ex)
{
throw ex;
}
return validationResult;
}
public override bool IsValid(object value)
{
if (value is int)
{
var stringValue = "" + (int)value;
var length = stringValue.Length;
if (length >= _Min && length <= _Max)
{
return true;
}
}
return false;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules
(ModelMetadata metadata, ControllerContext context)
{
var errorMessage = ErrorMessageString;
var maxDigitRule = new ModelClientValidationRule();
maxDigitRule.ErrorMessage = errorMessage;
maxDigitRule.ValidationType = "maxdigit";
maxDigitRule.ValidationParameters.Add("max", _Max);
maxDigitRule.ValidationParameters.Add("min", _Min);
yield return maxDigitRule;
}
}
为了启用客户端验证,我添加了一个不显眼的适配器
$(function () {
$.validator.addMethod("maxdigits", function (value, element, param) {
if (!value) return false;
console.log(param.min);
return false;
});
$.validator.unobtrusive.adapters.addMinMax("maxdigit", "maxdigits", "maxdigits", "maxdigits");
});
任何建议请