如果password为空字符串,则ModelState.IsValid为true

时间:2013-06-18 07:38:57

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 modelstate

我将登录模型传递给mvc4默认登录方法

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && _webSecurity.login(model))
        {
            return RedirectToLocal(returnUrl);
        }

        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View(model);
    }

我的模型如下所示

var _loginModel = new LoginModel
        {
            UserName = abc@gmail.com,
            Password = ""
        };

但ModelState.IsValid返回true。我不知道为什么。帮帮我

提前致谢。

修改

这是我的LoginModel

 public class LoginModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

1 个答案:

答案 0 :(得分:1)

模型绑定时将使用模型中定义的验证属性,你不必手动完成。

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

对于更复杂的验证,您还可以添加如下所示的正则表达式过滤器:

    [RegularExpression(@"^[^\<\>]*$", ErrorMessage = "May not contain <,>")]

这将匹配Windows组策略密码过滤器,例如:

    (?=^.{6,255}$)((?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))^.*