我正在开发一个简单的验证器。它适用于服务器端请求,但由于禁止回发,它不适用于客户端。.Net 的RequiredAttribute
验证器在客户端工作,不需要回发。
如何更改我的验证器以使其工作?
我的验证器获取一个字符串并检查它是否至少有 5 个字符长。
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field |
AttributeTargets.Parameter, AllowMultiple = false)]
public class MyValidatorAttribute : ValidationAttribute
{
private readonly int _length = 0;
public MyValidatorAttribute(int length)
{
_length = length;
}
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
if (value != null)
{
string data = (string)value;
if (data.Length < _length)
{
return new ValidationResult("length is short");
}
}
return ValidationResult.Success;
}
}
public class MyValidator : DataAnnotationsModelValidator<MyValidatorAttribute>
{
int minlength = 5;
string errorMsg = string.Empty;
public MyValidator(ModelMetadata metadata,
ControllerContext context,
MyValidatorAttribute attribute)
: base(metadata, context, attribute)
{
errorMsg = attribute.ErrorMessage;
}
public override IEnumerable<ModelClientValidationRule>
GetClientValidationRules()
{
ModelClientValidationRule validationRule =
new ModelClientValidationRule();
validationRule.ErrorMessage = errorMsg;
validationRule.ValidationType = "MyValidator";
validationRule.ValidationParameters.Add("minlength", minlength);
return new[] { validationRule };
}
}