我正在尝试使用我的自定义数据注释使客户端验证工作,我面临的问题是,每当我有一个非必需实体并提交我的请求(将非必需字段留空)时,客户端部分我的代码启动并尝试验证空白!我怎样才能避免这种情况?意思是,如果用户没有输入任何内容,那么不验证?
谢谢!
客户端代码:
$.validator.addMethod("emailvalid", function (value, element, params) {
var regex = /^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-zA-Z0-9]{1}[a-zA-Z0-9\-]{0,62}[a-zA-Z0-9]{1})|[a-zA-Z])\.)+[a-zA-Z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/;
return regex.test(value);
});
$.validator.unobtrusive.adapters.addBool("emailvalid");
服务器端代码:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class EmailValidAttribute : ValidationAttribute, IClientValidatable
{
private Regex Regex { get; set; }
private string pattern {
get {
return @"^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-zA-Z0-9]{1}[a-zA-Z0-9\-]{0,62}[a-zA-Z0-9]{1})|[a-zA-Z])\.)+[a-zA-Z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$";
}
}
public EmailValidAttribute(string errorMessage)
: base(errorMessage)
{
this.Regex = new Regex(this.pattern);
}
public override bool IsValid(object value)
{
var stringValue = Convert.ToString(value);
// automatically pass if value is null or empty. RequiredAttribute should be used to assert an empty value
if (string.IsNullOrWhiteSpace(stringValue))
{
return true;
}
var m = Regex.Match(stringValue);
// looking for an exact match, not just a search hit
return (m.Success && (m.Index == 0) && (m.Length == stringValue.Length));
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ValidationType = "emailvalid";
rule.ErrorMessage = ErrorMessageString;
yield return rule;
}
}