簡體   English   中英

使用 DataAnnotations 和 DataType 驗證電子郵件模型

[英]Email model validation with DataAnnotations and DataType

我有以下型號:

public class FormularModel
{
    [Required]
    public string Position { get; set; }
    [Required]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    [Required]
    public string Webcode { get; set; }
}

所需的驗證工作正常。 但是當我嘗試使用 DataType 時它沒有反應。

這是我用於電子郵件控件的剃刀代碼:

   @Html.TextBoxFor
          (model => model.Email, 
           new { @style = "width: 175px;", @class = "txtField" }
          ) * 

所以,有人知道答案嗎?

TIA

DataType屬性用於格式化目的,而不是用於驗證。

我建議您使用ASP.NET MVC 3 Futures進行電子郵件驗證。

示例代碼:

[Required]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }

如果您碰巧使用.NET Framework 4.5 ,現在有一個內置的EmailAddressAttribute位於System.ComponentModel.DataAnnotations.EmailAddressAttribute

DataAnnotationsExtensions項目有一個您可以使用的Email 屬性

我查看了源代碼(由 Reflector 逆向工程),實際上甚至沒有實現DataType變體! (這是為DateType.Date

所以它不會起作用。

我個人將RegexValidation用於電子郵件。


為清楚起見,這里是類DataTypeAttributeIsValid的實現:

public override bool IsValid(object value)
{
    return true;
}

我使用了這個正則表達式模式,它將允許一些較新的更長的擴展(.mynewsite 等)。

@"^[\w-_]+(\.[\w!#$%'*+\/=?\^`{|}]+)*@((([\-\w]+\.)+[a-zA-Z]{2,20})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$"

Not Valid ,其中包括:

  • 電子郵件@com
  • email-o'neil@mysite.com <-- 不喜歡打勾,哦,好吧。

有效的例子:

  • 電子郵件@m.superlongextension

我認為您需要在 html 代碼中添加一個組件Html.ValidationMessageFor 此組件顯示驗證。

代碼可能是(使用剃刀):

@Html.TextBoxFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)

嘗試一下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM