开发者

using DataAnnotations to validate Model, not working

I have this code on an Entity created using 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; }
    }
}

Members properties in the Member entity are Email and Password so far.

I'm trying to use the data annotations to return a validation message back to the view and have created a unit test like so:

    [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);
    }

This is failing, when I step into the controller ModelState.IsValid is always true. Here's my controller action:

 [HttpPost]
         public ActionResult Register(Member model)
         {
             if (ModelState.IsValid)
             { //reg开发者_如何学Goister
             }

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

Why is this not working?


Check out this tutorial

The model binder is not being invoked so the validation is not taking place.

You can do it manually using the following

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜