我有以下代码
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)]
[Display(Name = "Password")]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
当我显示表单时,客户端验证有效,但是当我在服务器端测试它时,它总是有效的(尝试使用Password = pass1234和ConfirmPassword = nonmatchingpassword)
我还在http://foolproof.codeplex.com/尝试了其他一些属性,例如EqualTo,但同样的问题。
我已经包含方法
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model)
{
if (WebSecurity.IsAuthenticated)
{
return RedirectToAction("Index", "Home");
}
if (ModelState.IsValid)
{
// register user...
}
model.Countries = this.Countries.FindAll().OrderBy(c => c.Name);
return View(model);
}
这就是我渲染的方式
@using (Html.BeginForm(null, null, FormMethod.Post, new { @class = "form", @id = "register-form" }))
{
@Html.AntiForgeryToken()
<ul class="form-fields">
...
<li class="form-field">
@Html.LabelFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
@Html.EditorFor(m => m.Password)
</li>
<li class="form-field">
@Html.LabelFor(m => m.ConfirmPassword)
@Html.ValidationMessageFor(m => m.ConfirmPassword)
@Html.EditorFor(m => m.ConfirmPassword)
</li>
...
<li class="form-actions">
<button class="submit">register</button>
</li>
</ul>
}
任何想法都可能出错?我正在使用MVC4 RC。
答案 0 :(得分:1)
这就是Microsoft在其默认MVC项目模板中的作用:
[PropertiesMustMatch( "Password", "ConfirmPassword", ErrorMessage = "The password and confirmation password do not match." )]
public class RegisterModel
{
[Required]
[DisplayName( "User name" )]
public string UserName { get; set; }
[Required]
[DataType( DataType.EmailAddress )]
[DisplayName( "Email address" )]
public string Email { get; set; }
[Required]
[ValidatePasswordLength]
[DataType( DataType.Password )]
[DisplayName( "Password" )]
public string Password { get; set; }
[Required]
[DataType( DataType.Password )]
[DisplayName( "Confirm password" )]
public string ConfirmPassword { get; set; }
}
我不确定你是如何进行服务器端测试的。如果这对您不起作用,也许您可以发布失败的测试?
答案 1 :(得分:0)
在第二项上取出StringLength。你不需要它,因为第一个项目已经拥有它。
答案 2 :(得分:0)
派对有点晚了,但我只是遇到了类似的问题。这是由jquery unobstrusive javascript文件中的错误引起的。更高版本将修复它,我刚刚运行
Install-Package jQuery.Validation.Unobtrusive
安装了v2,这对我来说很好。您的里程可能会有所不同。
此问题已得到妥善回答here。