Search code examples
javascriptjqueryhtmlforms

Validate required fields before JQuery submit form


I have a form with required fields like this:

<form id="testForm" NAME="testForm" ACTION="./test2.html" METHOD="post">
    <INPUT TYPE="text" Name="name" required="yes" />
    <INPUT TYPE="text" Name="name2"  />

    <INPUT class="btn btn-primary" TYPE="button" onclick="jsSubmit();" VALUE="Submit" ID="SubmitButton1">
</form>

If I click on Submit, it won't submit if the input "name" is empty which is what I want.

But if I do it in JQuery:

function jsSubmit(){
    if(/*Some necessary validation for other fields*/){
        // submit form
        $("#testForm").submit();
    } else {
        // alert date error
        $("#msgError").html('Error');
        $("#defaultErrors").modal();
    }
}

In this case, the form submits even though the input "name" is empty. How can I make the form validate the required fields in my JS/Jquery?

Thanks


Solution

  • I may be going about this the wrong way due to limited information, but could you do something like this:

    Use jQuery.submit so that any time the user submits the form your function is called.

    Then you can either prevent the submit, or let it continue based on your custom validation. This will allow you to leverage the default browser validation methods.

    jQuery("#testForm").submit(function (evt) {
    
      //At this point the browser will have performed default validation methods.
      
      //If you want to perform custom validation do it here.
      if (jQuery("input[Name='name']").val().length < 4) {
        alert("first Input must have 4 characters according to my custom validation!");
        evt.preventDefault();
        return;
      }
      alert("Values are correct!");
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="testForm" NAME="testForm" ACTION="./test2.html" METHOD="post">
        <INPUT TYPE="text" Name="name" required="yes" minlength="3"/>
        <INPUT TYPE="text" Name="name2"  />
    
        <!-- Change type to submit -->
        <INPUT class="btn btn-primary" TYPE="submit" VALUE="Submit" ID="SubmitButton1"/>
    </form>