C# 使用 DataAnnotations 和 DataType 验证电子邮件模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8989081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:28:24  来源:igfitidea点击:

Email model validation with DataAnnotations and DataType

c#asp.net-mvcvalidationemailmodel

提问by lifeofbenschi

I have following model:

我有以下型号:

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

Required validation works fine. But when i try with DataType it doesn't react.

所需的验证工作正常。但是当我尝试使用 DataType 时它没有反应。

Here is my razor code for the email control:

这是我用于电子邮件控件的剃刀代码:

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

So, anyone know an answer?

所以,有人知道答案吗?

TIA

TIA

采纳答案by Leniel Maccaferri

DataTypeattribute is used for formatting purposes, not for validation.

DataType属性用于格式化目的,而不是用于验证。

I suggest you use ASP.NET MVC 3 Futuresfor email validation.

我建议您使用ASP.NET MVC 3 Futures进行电子邮件验证。

Sample code:

示例代码:

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


If you happen to be using .NET Framework 4.5, there's now a built in EmailAddressAttributethat lives in System.ComponentModel.DataAnnotations.EmailAddressAttribute.

如果您碰巧正在使用.NET Framework 4.5,那么现在有一个内置EmailAddressAttributeSystem.ComponentModel.DataAnnotations.EmailAddressAttribute.

回答by Aliostad

I have looked at the source code (reverse engineered by Reflector) and DataTypevariants are actually not even implemented! (This was for DateType.Date)

我查看了源代码(由 Reflector 逆向工程),DataType实际上甚至没有实现变体!(这是为了DateType.Date

So it is not going to work.

所以它不会起作用。

I would personally use RegexValidationfor email.

我个人会RegexValidation用于电子邮件。



For clarity, here is the implementation of IsValidin class DataTypeAttribute:

为清楚起见,这里是IsValidin class的实现DataTypeAttribute

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

回答by jrummell

The DataAnnotationsExtensionsproject has an Email attributethat you can use.

DataAnnotationsExtensions项目有一个电子邮件属性,您可以使用。

回答by Wmanuelcr

I think you need to add at html code one componente Html.ValidationMessageFor. This component shows the validation.

我认为您需要在 html 代码中添加一个 componente Html.ValidationMessageFor。此组件显示验证。

The code may be (using razor):

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

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

try it.

尝试一下。