Question

I am passing login model to mvc4 default login method

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

My Model looks like following

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

but ModelState.IsValid is returning true . I don't know why . Help me

Thanks in advance .

Edit

Here is my 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; }
}
Was it helpful?

Solution

The validation Attribute defined in the model will be apllied while Model Binding, u don't have to do this manualy.

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

For more complex validation you also could add a regex filter like this:

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

This would match windows group policy password filter for example:

    (?=^.{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]))^.*
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top