views:

508

answers:

1

Hi Everyone,

I am trying to add some simple validation to my asp.net mvc form and am having trouble getting the .input-validation-error class to be added to my inputs. The validation-summary-errors and .field-validation-error work fine. Thanks in advance for your help!

Edit: Thanks for everyone's help!!! I had to add this line to the controller to avoid the error:

ModelState.SetModelValue("txtEmailOrDealerID", collection.ToValueProvider()["txtEmailOrDealerID"]);

The View:

<%using (Html.BeginForm("DealerLogin", "Home", FormMethod.Post))
  { %>
    <fieldset>
        <legend>Dealer Login</legend>
        <div class="row">
            <%=Html.Label("txtEmailOrDealerID", "E-Mail Or Dealer ID:")%>
            <%=Html.TextBox("txtEmailOrDealerID")%>
            <%=Html.ValidationMessage("txtEmailOrDealerID", "*")%>
        </div>
        <div class="row">
            <%=Html.Label("txtPassword", "Password:")%>
            <%=Html.Password("txtPassword")%>
            <%=Html.ValidationMessage("txtPassword", "*")%>
        </div>
        <div class="centerbutton">
            <input type="submit" id="btnSubmitDealer" value="Login"/>
        </div>
    </fieldset>
<%} %>

The Controller:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DealerLogin(FormCollection collection)
{
    if (string.IsNullOrEmpty(collection["txtEmailOrDealerID"].Trim()))
        ModelState.AddModelError("txtEmailOrDealerID", "E-Mail Address or Dealer ID is required.");
    if (string.IsNullOrEmpty(collection["txtPassword"].Trim()))
        ModelState.AddModelError("txtPassword", "Password is required.");
    if (ModelState.IsValid)
        return Redirect("~/MyUploads");
    else
        return View("Index");
}

The CSS:

/*Validation*/
.field-validation-error{color: #ff0000;}
.input-validation-error{border: 1px solid #ff0000; background-color: #ffeeee;}
.validation-summary-errors{color: #ff0000;}

The HTML.Label Extension Method:

public static string Label(this HtmlHelper helper, string forControl, string text)
{
    return String.Format("<label for='{0}'>{1}</label>", forControl, text);
}
+1  A: 

From the top of my head, the AddModelError id parameter should match the id of the input. So in your case, it should be changed to:

ModelState.AddModelError("txtEmailOrDealerID", "E-Mail Address or Dealer ID is required.");
Razzie