如何在接受多个电子邮件地址的字段上实现 MVC 非侵入式验证

How to implement MVC unobtrusive validation on a field that accepts multiple emails addresses

我为销售团队创建了一个 MVC 网络应用程序,用于将潜在客户输入系统,同时向他们发送跟进消息。一项要求是能够在发送的消息上抄送多个潜在客户。

应用程序的其余部分使用不显眼的验证,这在标准 HTML5 输入类型(例如 "email" 上非常有效。问题是没有标准输入类型可以自动验证多个电子邮件地址,就像您在电子邮件应用程序中看到的那样。

解决方案是创建自定义验证属性并将其注册到客户端,以便可以不显眼地对其进行验证。

  1. 创建自定义验证属性:

    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;
    
    namespace CustomValidation.BLL {
        public class MultiEmailValidator : ValidationAttribute, IClientValidatable{
    
            protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
                return new ValidationResult("");
            }
    
            public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
                ModelClientValidationRule mvr = new ModelClientValidationRule();
                mvr.ErrorMessage = "Enter valid email addresses separated by semi-colons.";
                mvr.ValidationType = "multiemail";
    
                return new[] { mvr };
            }
        }
    }
    
  2. 在客户端注册自定义验证:

    $(function () { 
        jQuery.validator.addMethod('multiemail', function (value, element, params) {            
            // emails should be separated by either ';' or ','
            var email = value.split(/[;,]+/);
            valid = true;
    
            // call the standard jquery validator method on each email entered
            for (var i in email) {
                value = email[i];
                valid = valid && jQuery.validator.methods.email.call(this, $.trim(value), element);
            }
            return valid;
        }, '');
    
        jQuery.validator.unobtrusive.adapters.add('multiemail', function (options) {
            options.rules['multiemail'] = {};
            options.messages['multiemail'] = options.message;
        });
    }(jQuery));
    
  3. 在模型上设置属性:

    [Display(Name = "Carbon Copy")]        
    [MultiEmailValidator]
    public string CarbonCopy { get; set; }
    
  4. 向视图添加输入:

    <div class="form-group col-lg-10">
        @Html.LabelFor(p => p.CarbonCopy, new { @class = "sr-only" })
    
        @Html.TextBoxFor(p => p.CarbonCopy, new { @class = "form-control input-sm", @placeholder = "Carbon Copy" })
    
        @Html.ValidationMessageFor(p => p.CarbonCopy)
    </div>
    

结果: Invalid Emails

结果: Valid Emails