客户端

时间:2016-10-19 15:32:47

标签: c# asp.net-mvc client-side-validation validationattribute

晚上好!

我已创建以下验证属性,以检查电子邮件列表是否有效。

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public class EmailAddressListAttribute : ValidationAttribute, IClientValidatable
{
    private const string RegexPattern = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*" +
                                        @"@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        ErrorMessage = $"{validationContext.DisplayName} contains invalid email addresses";

        var emailList = value.ToString().Split(';');
        return emailList.Where(e => !IsValidEmail(e))
            .ToList()
            .Count == 0 ? null : new ValidationResult(ErrorMessage);
    }

    private static bool IsValidEmail(string emailAddress)
    {
        return Regex.IsMatch(emailAddress, RegexPattern, RegexOptions.IgnoreCase);
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = ErrorMessage,
            ValidationType = "emailaddresslist"
        };
    }
}

我希望能够在客户端使用它,但我不确定我是如何做到这一点的。任何建议都将不胜感激。

干杯,

ž

修改

我已将以下JS代码添加为文件,并在我的视图中呈现它。它在页面加载时运行,但在提交表单时似乎没有做任何事情。

(function ($) {
$.validator.unobtrusive.adapters.addSingleVal("emailaddresslist");

$.validator.addMethod("emailaddresslist", function (value, element, params) {
    return false;
});
}(jQuery));

1 个答案:

答案 0 :(得分:2)

我搞定了!这是我的属性

的代码
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class EmailAddressListAttribute : ValidationAttribute, IClientValidatable
{
    private const string DefaultErrorMessage = "{0} contains invalid email addresses.";
    private const string RegexPattern = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*" +
                                        @"@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";

    public EmailAddressListAttribute()
      : base(DefaultErrorMessage)
    {
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, name);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        ErrorMessage = $"{validationContext.DisplayName} contains invalid email addresses";

        if (value.ToString().IsNullOrWhiteSpace()) return null;

        var emailList = value.ToString().Split(';');

        return emailList.Where(e => !IsValidEmail(e))
            .ToList()
            .Count == 0 ? null : new ValidationResult(ErrorMessage);
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var clientValidationRule = new ModelClientValidationRule()
        {
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "emailaddresslist"
        };

        clientValidationRule.ValidationParameters.Add("otherproperty", "");

        return new[] { clientValidationRule };
    }

    private static bool IsValidEmail(string emailAddress)
    {
        return Regex.IsMatch(emailAddress, RegexPattern, RegexOptions.IgnoreCase);
    }
}

这是客户端的jquery。

(function ($) {
$.validator.addMethod("emailaddresslist", function (value, element, params) {
    if (!this.optional(element)) {
        if (value == "") return true;
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        var emailAddressList = value.split(";")
        var arrayLength = emailAddressList.length;
        for (var i = 0; i < arrayLength; i++) {
            if (!re.test(emailAddressList[i].trim())) return false;
        }
    }
    return true;
});
$.validator.unobtrusive.adapters.addSingleVal("emailaddresslist", "otherproperty");
}(jQuery));