模型上的DataTypeAttribute是否在MVC 3中进行验证?

Tra*_*vis 13 c# validation asp.net-mvc-3

默认的ASP.net MVC 3 Internet应用程序模板包括以下模型:

public class RegisterModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email address")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在帐户/注册操作中,它要求提供电子邮件地址,但似乎您可以在此字段中键入任何内容,它将接受它.

DataType(DataType.EmailAddress)是否实际触发验证?好像它没有.如果它不验证类型,那么它的目的是什么?

Jak*_*keJ 11

据我所知,DataType属性用于格式化,但仅限于您使用时@Html.EditorFor(model => model.Field).

模型字段,cshtml和生成的HTML中的示例:

型号领域:

[Required]
[DataType(DataType.Text)]
[Display(Name = "Name")]
public string Name { get; set; }

[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }

[Required]
[DataType(DataType.MultilineText)]
[Display(Name = "Description")]
public string Desc { get; set; }
Run Code Online (Sandbox Code Playgroud)

CSHTML:

<div class="form-section">
    @Html.LabelFor(x => x.Name)
    @Html.EditorFor(x => x.Name)
</div>

<div class="form-section">
    @Html.LabelFor(x => x.Password)
    @Html.EditorFor(x => x.Password)
</div>

<div class="form-section">
    @Html.LabelFor(x => x.Desc)
    @Html.EditorFor(x => x.Desc)
</div>
Run Code Online (Sandbox Code Playgroud)

产生的HTML:

<div class="form-section">
    <label for="Name">Name</label>
    <input class="text-box single-line" id="Name" name="Name" type="text" value="">
</div>
<div class="form-section">
    <label for="Password">Password</label>
    <input class="text-box single-line password" id="Password" name="Password" type="password" value="">
</div>
<div class="form-section">
    <label for="Desc">Description</label>
    <textarea class="text-box multi-line" id="Desc" name="Desc"></textarea>
</div>
Run Code Online (Sandbox Code Playgroud)

我知道这是一个老帖子,但也许我可以通过这种方式为其他人的情况发光

编辑:

可能是连接到这些,但只有客户端的一些验证.不要依赖这些属性进行实际验证,这应始终在服务器端完成(客户端仅用于用户体验)


Eri*_*ren 0

默认模板不会将正确的 Validate.js 脚本添加到母版页。数据注释仅输出 JavaScript 读取的 HTML 以进行客户端验证。

在控制器操作中,您需要执行 Model.IsValid 以确保服务器端验证。