mvc [DataType(DataType.EmailAddress) no validation

后端 未结 5 892
情歌与酒
情歌与酒 2020-12-15 16:56

I\'m using this code on an email field:

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = \"Email address\")]
    public string Email          


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 17:31

    As Felix mentioned, the problem is on the View level, you need to use EditorFor() in your View instead of TextBoxFor(), the EditorFor() will render:

    
    

    which will trigger the validation, while TextBoxFor() will render:

    
    

    So in order to validate your entered email address, you need (in combination with EditorFor()) to use only:

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

    This way, your entered value for email will be always validated, but if you don't enter a value for email, nothing will happen (unless you specified the [Required] attribute), the form will be submitted with an empty email address.

提交回复
热议问题