为什么DataType.Password仅在服务器端验证?

时间:2014-08-07 11:42:51

标签: c# .net asp.net-mvc validation data-annotations

我的模特为

[Required]
[EmailAddress]
[Remote("EmailValidation", "Account", ErrorMessage = "{0} already has an account, please enter a different email address.")]
[Display(Name = "Email")]
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")]
[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }

以及注册表格:

<form id="registrationForm">
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true, String.Empty, new { @class = "text-danger text-center" })
    @Html.HiddenFor(m => m.ForModal, new { @Value = true })
    <div class="form-group text-center">
        <div class="input-group margin-top-10 margin-bottom-5">
            <span class="input-group-addon"><i class="fa fa-user"></i></span>
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control", placeholder = "Email", @readonly = "readonly" })
        </div>
        @Html.ValidationMessageFor(m => m.Email, null, new { @class = "text-danger" })
        <div class="input-group margin-top-10 margin-bottom-5">
            <span class="input-group-addon"><i class="fa fa-lock"></i></span>
            @Html.PasswordFor(m => m.Password, new { @class = "form-control", placeholder = "Password" })
        </div>
        @Html.ValidationMessageFor(m => m.Password, null, new { @class = "text-danger" })
        <div class="input-group margin-top-10 margin-bottom-5">
            <span class="input-group-addon"><i class="fa fa-lock"></i></span>
            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control", placeholder = "Confirm Password" })
        </div>
        @Html.ValidationMessageFor(m => m.ConfirmPassword, null, new { @class = "text-danger" })
    </div>
    <div class="text-right">
        <button type="submit" class="btn-u btn-u-orange btn-u-wide" title="Join">Join</button>
    </div>
</form>

当我键入短密码 - 验证触发时,当我输入不同的confirmPassword作为密码 - 验证触发,但当我只键入数字123456时,客户端没有任何事情发生,只是在服务器端,毕竟我收到错误。

http://i.imgur.com/jY8bymy.png(截图链接)

为什么我可以在客户端获得验证DataType.Password?


当我在互联网上搜索这样的问题时,我得到的解决方案就像use Html.PasswordFor or Html.EditorFor instead of Html.TextBoxFor

1 个答案:

答案 0 :(得分:12)

DataType属性不用于框中的验证,它主要用于渲染。例如,如果您使用EditorFor在内部呈现属性,则会使用DataType属性来确定应呈现的输入类型,即<input type="password" ... />PasswordFor基本上做同样的事情,但不需要DataType属性。

您的长度验证适用于客户端,因为StringLength属性不是DataType。如果您想强制执行特定的数据类型验证,我建议您先使用RegularExpressionAttribute,然后考虑实施自己的custom validator