![](/img/trans.png)
[英]Validating an email string in .net using EmailAddressAttribute, but not on an attribute
[英]jQuery Validation of email TLD vs. .Net 4.5 EmailAddressAttribute
我當前在視圖模型中的字符串屬性上使用EmailAddressAttribute驗證類。 我遇到的問題是,在客戶端,jQuery驗證允許使用以下格式的電子郵件“ someDude @ test”,但是在提交視圖模型時,ModelState失敗,因為EmailAddressAttribute不接受該格式的地址。
我能想到的唯一解決方法是在服務器端應用正則表達式或創建自定義jQuery驗證規則。
是否有更清潔的解決方案?
因此,我最終接受了jwats1980的建議,並創建了一個與jQuery驗證一致的新的自定義驗證屬性。 下面是我的代碼:
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.