user2998990
user2998990

Reputation: 980

Required Attribute not firing

The following is my class. I am trying to make a small login form. I have a class LoginApp which has username and password. Both I have made required.

[Required(ErrorMessage="This Is a required field")]
[Display(Name="User Name")]
public string userName { get; set; }

[Required]
[Display(Name = "PassWord")]
public string passWord { get; set; }

Following is my controller where i have used tryUpdateModel for checking.

public ActionResult Login(Models.LoginApp LA)        
{
  LoginApp LAPP = new LoginApp();
  bool g =  TryUpdateModel(LAPP);
  if (ModelState.IsValid)
  {           
    if (LA.userName == "admin" && LA.passWord == "admin")
      return RedirectToAction("LoginSuccessful", new { userName = LA.userName});
    else
      return RedirectToAction("Index");
  }
  else
    return RedirectToAction("Index");        
  }

Here is the view.

<div class="container">
  @using (Html.BeginForm("Login", "Login"))
  {
    @Html.ValidationSummary(true)
    <div class="row">
      <div class="form-group ">
        @Html.Label("User Name", new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
          @Html.TextBoxFor(Model => Model.userName, "", new { @class = "form-control" })
          @Html.ValidationMessageFor(Model => Model.userName)
        </div>
      </div>
      <br />
      <br />
      <div class="form-group ">
        @Html.Label("PassWord", new { @class = "col-md-2 control-label" })
        <div class="col-md-10 ">
          @Html.PasswordFor(u => u.passWord, new { @class = "form-control" })
          @Html.ValidationMessageFor(Model => Model.passWord)
        </div>
      </div>
      <br />
      <br />
      <div class="form-group ">
        <div class="col-md-offset-2 col-md-10">
          <input type="submit" value="Log in" class="btn btn-default" />
          <input type="button" id="btn" value="Reset" onclick="" class="btn btn-default" />
        </div>
      </div>
    </div>
  }
</div>

When I click the log in button without supplying the username or password it doesn't give me validation messages. Where I am going wrong.

Upvotes: 1

Views: 2683

Answers (1)

clement
clement

Reputation: 4266

You didn't include the validate.js and unobtrusiveon the page.

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

You should check if the ModelState.IsValid in the controller in order to ake the validation in back-end too (so in both side)

Upvotes: 1

Related Questions