Email model validation with DataAnnotations and DataType

前端 未结 4 1717
说谎
说谎 2020-12-01 06:08

I have following model:

public class FormularModel
{
    [Required]
    public string Position { get; set; }
    [Required]
    [DataType(DataType.EmailAddre         


        
相关标签:
4条回答
  • 2020-12-01 06:39

    DataType attribute is used for formatting purposes, not for validation.

    I suggest you use ASP.NET MVC 3 Futures for email validation.

    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 EmailAddressAttribute that lives in System.ComponentModel.DataAnnotations.EmailAddressAttribute.

    0 讨论(0)
  • 2020-12-01 06:39

    The DataAnnotationsExtensions project has an Email attribute that you can use.

    0 讨论(0)
  • 2020-12-01 06:40

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

    So it is not going to work.

    I would personally use RegexValidation for email.


    For clarity, here is the implementation of IsValid in class DataTypeAttribute:

    public override bool IsValid(object value)
    {
        return true;
    }
    
    0 讨论(0)
  • 2020-12-01 06:41

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

    The code may be (using razor):

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

    try it.

    0 讨论(0)
提交回复
热议问题