我的模型是
[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>
当我输入短密码时 - 验证触发,当我输入与密码不同的 confirPassword - 验证触发,但是当我只输入数字作为 123456
时,客户端没有任何反应,只是在服务器端,毕竟我得到了错误。
http://i.imgur.com/jY8bymy.png(截图链接)
为什么我可以在客户端获取验证DataType.Password?
当我在互联网上搜索此类问题时,我得到的解决方案是使用 Html.PasswordFor 或 Html.EditorFor 而不是 Html.TextBoxFor
。
最佳答案
DataType
属性不用于开箱即用的验证,它主要用于渲染。例如,如果您使用 EditorFor
要在内部呈现属性,它将使用 DataType
属性来确定它应该呈现什么类型的输入,即 <input type="password" ... />
. PasswordFor
基本上做同样的事情但不需要 DataType
属性。
您的长度验证在客户端工作,因为它由 StringLength
处理属性不是 DataType
.如果你想强制执行特定的数据类型验证,我建议你看看使用 RegularExpressionAttribute ,否则您将考虑实现自己的 custom validator .
关于c# - 为什么 DataType.Password 只在服务器端验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25181636/