提问人:larry 提问时间:1/12/2017 更新时间:1/12/2017 访问量:358
客户端验证 2 个不同的字符串长度在 MVC ASP.NET 不起作用
Client-side validation for 2 different string length not working ASP.NET MVC
问:
我正在尝试使用客户端验证在 MVC 5 ASP.NET 自定义 ValidationAttribute,但我不明白出了什么问题:验证工作正常,但仅限于服务器端。 我写了自定义属性:
public class UserStringLengthAttribute : ValidationAttribute {
private int _lenght1;
private int _lenght2;
public UserStringLengthAttribute(int lenght2, int lenght1)
{
_lenght2 = lenght2;
_lenght1 = lenght1;
}
public override bool IsValid(object value) {
var typedvalue = (string)value;
if (typedvalue.Length != _lenght1 || typedvalue.Length != _lenght2)
{
ErrorMessage = string.Format("The length must be {0} or {1}", _lenght1, _lenght2);
return false;
}
return true;
} }
和适配器:
public class UserStringLengthAttributeAdapter : DataAnnotationsModelValidator<UserStringLengthAttribute> {
public UserStringLengthAttributeAdapter(
ModelMetadata metadata,
ControllerContext context,
UserStringLengthAttribute attribute) :
base(metadata, context, attribute)
{
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
ModelClientValidationRule rule = new ModelClientValidationRule()
{
ErrorMessage = ErrorMessage,
ValidationType = "custom"
};
return new ModelClientValidationRule[] { rule };
} }
我在Global.asax.cs中注册了它:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(UserStringLengthAttribute),
typeof(UserStringLengthAttributeAdapter));
我在元数据中使用了它:
[Required]
[UserStringLength(11, 16)]
[Display(Name = "VAT or tax code")]
public string CodVat;
但是验证只在服务器端起作用,在客户端不起作用。有什么建议吗?
答: 暂无答案
评论
jqueryval
$.validator