1

I am creating an ASP.NET MVC 5 application. I need to write some jQuery or JavaScript that checks if the application's form is valid (using jQuery Validate) when the form is submitted. If the form is valid, then the form needs to simultaneously submit and show an alert box (for now). I have used this post so far to sculpt my code, but it is not working for me. This code is functioning correctly:

$('form').submit(function () {
  alert('test');
});

But this does not work for me:

$('form').submit(function () {
  if ($(this).valid()) {
    alert('the form is valid');
  }
});

I am getting the following error:

Uncaught TypeError: $(...).valid is not a function

I don't understand why this code worked for other people but it does not work for me. Where am I going wrong?

How can I get the submit button to simultaneously show the alert box and submit the form when the form is valid?

cryan
  • 119
  • 1
  • 13

1 Answers1

0

Which version of jquery are you using? I was getting the same error, when checked in the network tab of chrome browser, my app was using jquery 1.10.2. The jQuery validator works with 1.7.2, 1.8.3, 1.9.1, 1.11.1, 3.1.1 only. This is as per the plugin page - https://jqueryvalidation.org/

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
 <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/jquery.validate.js"></script>

 <script>
    $(document).ready(function () {

    $('#sampleForm').submit(function () {
        if ($(this).valid()) {
            alert('valid');
        }
        else {
            alert('not valid');
        }
    });
});
</script>
<div class="jumbotron">
  <h1>ASP.NET</h1>
  <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
  <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>

<div class="row">
  <form id="sampleForm">
    <input type="text" />
    <input type="submit" value="Submit" />
  </form>
</div>

If you are using VS MVC project, check the bundleConfig.cs, it downloads a different version of jQuery. Ensure that it downloads the required version of jQuery or comment the line in the config that downloads the jQuery for testing.

Raghav
  • 24
  • 3