Asp.NET MVC Client side validation is not working

Viewed 1589

whenever I am submitting the form without entering the required fields instead of giving an immediate client-side validation error it is going to the Httppost Actionresult Index method allowing to submit the form. After roundtrip to server-side then giving errors. I have added reference of jquery.validate.js, unobtrusive.js both libraries, and also set ClientValidationEnabled and UnobtrusiveJavaScriptEnabled value true inside web.config. YOUR KIND HELP WILL BE HIGHLY APPRECIATED

HTML :

  @model binaryquest.web.CustomModels.ContactVM
@{
    ViewBag.Title = "Home Page";
}

<div id="contact" class="form">
    <div class="container">
        <div class="row">
            <div class="col-lg-12">
                <h2>CONTACT</h2>
                <ul class="list-unstyled li-space-lg">
                    <li class="address">Don't hesitate to give us a call or just use the contact form below</li>
                    
                </ul>
            </div> <!-- end of col -->
        </div> <!-- end of row -->
        <div class="row">
            <div class="col-lg-8 offset-lg-2">

                <!-- Contact Form -->
                
                <form action="/Home/Index" method="post">
                    @Html.AntiForgeryToken()
                    @Html.ValidationMessage("expired", new { @class = "text-danger" })
                    @Html.ValidationMessage("CaptchaFail", new { @class = "text-danger" })

                    <div class="form-group">
                        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "required" })
                        @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "required" })
                        @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.Message, htmlAttributes: new { @class = "required" })
                        @Html.EditorFor(model => model.Message, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Message, "", new { @class = "text-danger" })
                    </div>

                    <div class="form-group checkbox">
                        <input type="checkbox" id="cterms" value="Agreed-to-Terms" required>I have read and agree to Leno's stated conditions in <a href="/Home/PrivacyPolicy">Privacy Policy</a>.
                        <div class="help-block with-errors"></div>
                    </div>

                    @Html.CheckBoxFor(model => model.IsTermsAccepted, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.LabelFor(model => model.IsTermsAccepted, htmlAttributes: new { @class = "required" })
                    @Html.ValidationMessageFor(model => model.IsTermsAccepted, "", new { @class = "text-danger" })

                    <div class="form-group">
                        <button type="submit" class="form-control-submit-button">SUBMIT MESSAGE</button>
                    </div>

                    <div class="form-message">
                        <div id="cmsgSubmit" class="h3 text-center hidden"></div>
                    </div>

                </form>
                <!-- end of contact form -->

            </div> <!-- end of col -->
        </div> <!-- end of row -->
    </div> <!-- end of container -->
</div>

@section scripts{

    
    <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
    <script src="//ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.js"></script>

    
}

MODEL :

public class ContactVM
    {
        [Required(ErrorMessage = "You must provide Name")]
        [DisplayName("Name")]
        public string Name { get; set; }

        
        [Required(ErrorMessage = "You must provide an Email address")]
        [DisplayName("Email")]
        [EmailAddress]
        public string Email { get; set; }

        [Required(ErrorMessage = "You must provide Message")]
        [DisplayName("Your Message")]
        public string Message { get; set; }


        [Display(Name = "Terms and Conditions")]
        [Range(typeof(bool), "true", "true", ErrorMessage = "You must accept the terms and conditions!")]
        public bool IsTermsAccepted { get; set; }
        
        

    }

CONTROLLER:

            public ActionResult Index()
            {
                return View();
            }

            [HttpPost]
            [AllowAnonymous]
            [ValidateAntiForgeryToken]
            public ActionResult Index(ContactVM model)
            {
               
                string sendGridKey ="";
                if (ModelState.IsValid)
                {
                    SendMail(model, sendGridKey);
                    return RedirectToAction("Thanks", "Home");
                }
    
                return View(model);
            }
3 Answers

You need to use the loaded javascript. Add to your view the following:

<script>
$(document).ready(function() {
   $.validator.unobtrusive.parse($("#myForm"));
}

function onSubmit(e) {
  $("#myForm").validate(); // this will validate the form and show the validation messages
  if($("#myForm").valid()) {
     $("#myForm").submit(); // submits the form
  }
  // stop the postback
  e.preventDefault();
}
</script>

Then on your form element:

<form id="myForm" onsubmit="onSubmit();" action="/Home/Index">

Seems validation scripts not loaded. Did you loaded in _layout.cshtml?

@RenderSection("scripts", required: false)

And try adding validation summery in starting of form

@Html.ValidationSummary(true, "", new { @class = "text-danger" })
Related