不确定这是否是预期的,但这对我来说是一个惊喜..
我正在使用RegistrationViewModel强力键入视图,但是当我尝试提交表单时,验证错误地在2个位置验证。
任何人都知道为什么会这样吗?
ViewModel类:
public class RegistrationViewModel
{
public RegisterModel RegistrationData { get; set; }
...
}
验证属性位于RegistrationData类的属性中:
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; }
[Required]
[Display(Name = "First name")]
[StringLength(20, ErrorMessage = "First name must be between 2 and 20 characters.", MinimumLength = 2)]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last name")]
[StringLength(20, ErrorMessage = "Last name must be between 2 and 20 characters.", MinimumLength = 2)]
public string LastName { get; set; }
}
查看:
@model PropertyManager_MVC.Areas.Account.ViewModels.RegistrationViewModel
<div class="editor-field">
@Html.TextBoxFor(m => m.RegistrationData.Email)
@Html.ValidationMessageFor(m => m.RegistrationData.Email)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.RegistrationData.Password)
</div>
<div class="editor-field">
@Html.PasswordFor(m => m.RegistrationData.Password)
@Html.ValidationMessageFor(m => m.RegistrationData.Password)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.RegistrationData.ConfirmPassword)
</div>
<div class="editor-field">
@Html.PasswordFor(m => m.RegistrationData.ConfirmPassword)
@Html.ValidationMessageFor(m => m.RegistrationData.ConfirmPassword)
</div>
答案 0 :(得分:2)
将此正则表达式添加到电子邮件属性,它将负责处理它。
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
[RegularExpression("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9]+(\\.[a-z]{2,4})$", ErrorMessage = "Not a valid email")]
public string Email { get; set; }
在“确认密码”字段前添加必需属性。
[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
Scottgu的例子来处理这个问题。 http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx