自定义属性的客户端验证
Client side validation for custom attribute
为什么我的客户端验证不起作用。
属性 是:
[Required(ErrorMessage = "Email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
[NonCompanyEmailAttribute(ErrorMessage = "Email address of customer required (not company employees)")]
public string EmailAddress
验证属性是:
public class NonCompanyEmailAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
bool containscompany = !((string)value).ToLower().Contains("@company.com");
return containscompany;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage,
ValidationType = "noncompanyemail"
};
}
}
在 JS 中我有:
$.validator.addMethod("noncompanyemail", function (value, element, params) {
return value.toLowerCase().indexOf('company.com' > -1);
});
$.validator.unobtrusive.adapters.add("noncompanyemail", function (options) {
options.rules["noncompanyemail"] = true;
options.messages["noncompanyemail"] = options.message;
});
包括 jquery.validate.js 和 jquery.validate.unobtrusive.js
我不确定您所说的 "not working" 是什么意思,但是您的 jquery 验证函数的格式似乎很奇怪。如果该值在任何地方包含 company.com,我假设您希望它为 return false(也称为无效)。如果是这样,您的方法应该类似于:
$.validator.addMethod("noncompanyemail", function (value, element, params) {
return (value.toLowerCase().indexOf('company.com') == -1);
});
为什么我的客户端验证不起作用。
属性 是:
[Required(ErrorMessage = "Email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
[NonCompanyEmailAttribute(ErrorMessage = "Email address of customer required (not company employees)")]
public string EmailAddress
验证属性是:
public class NonCompanyEmailAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
bool containscompany = !((string)value).ToLower().Contains("@company.com");
return containscompany;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage,
ValidationType = "noncompanyemail"
};
}
}
在 JS 中我有:
$.validator.addMethod("noncompanyemail", function (value, element, params) {
return value.toLowerCase().indexOf('company.com' > -1);
});
$.validator.unobtrusive.adapters.add("noncompanyemail", function (options) {
options.rules["noncompanyemail"] = true;
options.messages["noncompanyemail"] = options.message;
});
包括 jquery.validate.js 和 jquery.validate.unobtrusive.js
我不确定您所说的 "not working" 是什么意思,但是您的 jquery 验证函数的格式似乎很奇怪。如果该值在任何地方包含 company.com,我假设您希望它为 return false(也称为无效)。如果是这样,您的方法应该类似于:
$.validator.addMethod("noncompanyemail", function (value, element, params) {
return (value.toLowerCase().indexOf('company.com') == -1);
});