Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-evaluate the ModelState.IsValid property

I am trying to validate a user changing their password. The PasswordChange Class which this actionresult takes has 4 properties. one of which is the databasePassword which im compared against a "CurrentPassword" property which ensures the user can only change their password if they know their current password (pretty standard proceedure on websites)

Problem I have is the database password is only set (as shown) inside the ActionResult but the ModelState seems to get called before this so it returns false on "IsValid" because it sees the database password as "NULL" even after the database password is set

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult ChangePassword(PasswordChange model)
    {
        var User = GetPlayer().User;
        model.databasePassword = User.Password; 

        if (ModelState.IsValid)
        {
            //update the users password
            User.Updated = SystemDate.Current();
            User.Password = model.newPassword.ToLower();

            return Redirect("/Player");
        }
        else
        {
            return View(model);
        }
    }

How can I go about reevaluating it or getting it to evaluate when i want it to!

like image 950
Steve Avatar asked Mar 07 '11 21:03

Steve


2 Answers

Check the error and clear it if your assignment fixed it. Simplified check:

model.databasePassword = User.Password;
if (ModelState["databasePassword"].Errors.Count == 1)
{
    ModelState["databasePassword"].Errors.Clear();
}
like image 158
Gerard Avatar answered Oct 29 '22 23:10

Gerard


Create a PasswordChangeInput view model class and pass in what you need from the view, you can then have separate validation from your entity model. Then you can use something like automapper to map the input view model to the entity model after your satisfied the input data is valid.

To add: you could try and clear out the ModelState errors, set the databasePassword, and re validate. It's probably easier to figure out what is causing the default model binder to add an error for databasePassword and change it so it doesnt.

like image 1
Derek Beattie Avatar answered Oct 30 '22 00:10

Derek Beattie