简体   繁体   English

电子邮件TLD与.Net 4.5的jQuery验证EmailAddressAttribute

[英]jQuery Validation of email TLD vs. .Net 4.5 EmailAddressAttribute

I am currently using the EmailAddressAttribute validation class on a string property in my view model. 我当前在视图模型中的字符串属性上使用EmailAddressAttribute验证类。 The problem I am running into is that on the client-side, jQuery validation allows for emails in the following format, "someDude@test" however when the view model is submitted, the ModelState fails because EmailAddressAttribute does not accept addresses in that format. 我遇到的问题是,在客户端,jQuery验证允许使用以下格式的电子邮件“ someDude @ test”,但是在提交视图模型时,ModelState失败,因为EmailAddressAttribute不接受该格式的地址。

The only workaround I can think of is either applying a regex on the server side or create a custom jQuery validation rule. 我能想到的唯一解决方法是在服务器端应用正则表达式或创建自定义jQuery验证规则。

Is there a cleaner fix to this? 是否有更清洁的解决方案?

So I ended up taking jwats1980 advice and creating a new custom validation attribute that agrees with the jQuery validation. 因此,我最终接受了jwats1980的建议,并创建了一个与jQuery验证一致的新的自定义验证属性。 Below is my code: 下面是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Net.Mail;
using System.Web.Mvc;

namespace SWCGPExternal.Attributes
{
    public class CustomEmailAddressAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            if (value == null)
                return false;

            try
            {
                MailAddress m = new MailAddress((string)value);
                return true;
            }
            catch (FormatException)
            {
                return false;
            }
        }

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

            return new[] { clientValidationRule };
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM