1

我将登录模型传递给 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; }
}
4

1 回答 1

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]))^.*
于 2013-06-18T08:18:27.753 回答