使用DataAnnotations验证Model,不起作用

时间:2011-07-20 17:06:37

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

我在使用EF 4创建的实体上有此代码:

[MetadataType(typeof(MemberMetaData))]
public partial class Member
{
    public string ConfirmPassword { get; set; }

    [PropertiesMustMatch("Password", "ConfirmPassword", ErrorMessage = "Password and confirm password do not match.")]
    public class MemberMetaData
    {
        [Required(ErrorMessage = "Email is required.")]
        [DataType(DataType.EmailAddress, ErrorMessage = "Email is invalid.")]
        //[RegularExpression(@"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$")]
        public object Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [DisplayName("Password")]
        public object Password { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [DisplayName("Confirm Password")]
        public object ConfirmPassword { get; set; }
    }
}

到目前为止,会员实体中的会员属性是电子邮件和密码。

我正在尝试使用数据注释将验证消息返回给视图,并创建了一个单元测试,如下所示:

    [TestMethod]
    public void register_post_displays_error_when_email_not_entered()
    {
        // Arrange
        Member model = new Member()
        {
            Email = "",
            Password = "test123",
            ConfirmPassword = "test123"
        };
        // Act
        var result = _controller.Register(model) as ViewResult;
        // Assert
        Assert.AreEqual("Email is required.", result.ViewData.ModelState["Email"].Errors[0].ErrorMessage);
    }

这是失败的,当我进入控制器时,ModelState.IsValid始终为true。这是我的控制器动作:

 [HttpPost]
         public ActionResult Register(Member model)
         {
             if (ModelState.IsValid)
             { //register
             }

             // If we got this far, something failed, redisplay form
             return View("Register");
         }

为什么这不起作用?

1 个答案:

答案 0 :(得分:2)

查看此tutorial

未调用模型绑定器,因此未进行验证。

您可以使用以下

手动完成
var validationContext = new ValidationContext(user, null, null);
var validationResults = new List<ValidationResult>();
Validator.TryValidateObject(user, validationContext, validationResults);
foreach (var validationResult in validationResults)
{
    controller.ModelState.AddModelError(validationResult.MemberNames.First(), validationResult.ErrorMessage);
}