Javascript form validation not working?

this is my html contact _form

                                        <form action="#" method="post" id="contact_form" onsubmit="return validation()">
                     
                        <div class="contact_input_area">
                            <div class="row">
                              
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <input type="text" class="form-control" name="name" id="name" placeholder="Your Name" required>
                                          <span id="nameId"></span>
                                    </div>
                                  
                                </div>
                             
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <input type="email" class="form-control" name="email" id="email" placeholder="Your E-mail" required>
                                    </div>
                                    <span id="emailId"></span>
                                </div>
  
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <input type="number" class="form-control" name="mobile" id="mobile" placeholder="Your Mobile" required>
                                    </div>
                                    <span id="numberId"></span>
                                </div>
             
                                <div class="col-12">
                                    <div class="form-group">
                                        <input type="text" name="message" class="form-control" id="message" cols="30" rows="4"
       placeholder="Coaching Class Name " required>
                                    </div>
                                    <span id="msgId"></span>
                                </div>
                        
                                <div class="col-12">
                                    <button   type="submit" name="submit" value="submit" id="submit" class="btn submit-btn">Sign Up Now</button>


                                </div>
                            </div>
                        </div>
                       
                        
                    </form>

this is javascript code I wrote for validation of above form

     <script>
      function validation()
      {
      var name = document.getElementById('name').value;
       var email = document.getElementById('email').value;
       var mobile = document.getElementById('mobile').value;
       var msg = document.getElementById('message').value;




    if(name == "" ){
        document.getElementById('nameId').innerHTML = " **Please fill the Name";
        return false;
    }
     
     if(email == "" ){
        document.getElementById('emailId').innerHTML = " **Please fill email";
        return false;
    }

    if(email.indexof('@') <= 0 ){
        document.getElementById('emailId').innerHTML = " **Please fill email in proper format";
        return false;
    }

     if((email.charAt(email.length-4) != '.' ) && (email.charAt(email.length-4) != '.' )){
        document.getElementById('emailId').innerHTML = " **Please fill email in proper format";
        return false;
    }
     

      if(mobile == "" ){
        document.getElementById('numberId').innerHTML = " **Please fill your mobile number";
        return false;
    }

       if(mobile.length != 10 ){
        document.getElementById('numberId').innerHTML = " **Mobile number should be 10 digits";
        return false;
    }


     if(msg == "" ){
        document.getElementById('msgId').innerHTML = " **Please fill the class name";
        return false;
        }




         }
         </script>

I am not getting that where I went wrong the valiation are not working ?
What should I do gide me please ?

I’ve put together a sample page with your code, and the validation seems to be working there.

Is there something specific about it that doesn’t seem to work?

1 Like

On further investigation, indexof needs to be indexOf instead, and all email addresses that don’t end with three characters after a fullstop, will fail to work. Say goodbye to all john@telecom.co.uk addresses for example.

1 Like

hey thanks for replying yes its working seperately but I guess I found the reason why its not working in my case actually I am sending email through this form for that I have one script throug this script the form is submitting using ajax call

this is the script I am using

                                     <script>
                      $(document).ready(function () {    
                        $("#submit").click(function (e) {

                           e.preventDefault();
                            var form_data = $('form').serialize(); // if(name && email && mobile && message ){
                            // alert(form_data);
                              if ($("#name").val() )
                                  {
                                       $.ajax({
                                               type: "post", 
                                                url: "email.php",
                                                dataType: "json", // Add datatype
                                                 data: form_data,
                                                   success: function () {
                                                    $('#mymodal').modal('show');
                                                    
                                                      }

                                               }); 
                                  }
                              document.getElementById("contact_form").reset();
                           });
                         });
                    </script>

the script is working properly but form is still submiting if the fields are empty so how to fix it using this validation ?

There are other ways to submit the form than by clicking on the submit button.

I recommend that you don’t use the submit button click, and use the form submit event instead.

yes that would be good choice but I have tried another way with jquery.I included the jquery validation code in the above script and validations are woring properly but still the form is submiting and resetting even if there is a invalid field

this is updated script

                                              <script>
                      $(document).ready(function () {    
                        $("#submit").click(function (e) {

                           e.preventDefault();
                            var form_data = $('form').serialize(); // if(name && email && mobile && message ){
                            // alert(form_data);


                              var name = $('#name').val();
                              var email = $('#email').val();
                              var mobile = $('#mobile').val();
                              var msg = $('#message').val();

                              $(".error").remove();

                              if (name.length < 1) {
                                $('#name').after('<span class="error">This field is required</span>');
                                 }

                                 if (email.length < 1) {
                                  $('#email').after('<span class="error">This field is required</span>');
                                  } else {
                                        var regEx = /^[A-Z0-9][A-Z0-9._%+-]{0,63}@(?:[A-Z0-9-]{1,63}\.){1,125}[A-Z]{2,63}$/;
                                             var validEmail = regEx.test(email);
                                               if (!validEmail) {
                                             $('#email').after('<span class="error">Enter a valid email</span>');
                                             }
                                           }
                                 
                                 if (msg.length < 1) {
                                $('#message').after('<span class="error">This field is required</span>');
                                 }

                              if ($("#name").val() )
                                  {
                                       $.ajax({
                                               type: "post", 
                                                url: "email.php",
                                                dataType: "json", // Add datatype
                                                 data: form_data,
                                                   success: function () {
                                                    $('#thank_you').modal('show');
                                                      // window.location.href='#thank_you';   
                                                      }

                                               }); 
                              document.getElementById("contact_form").reset();
                                       
                                  }
                           });
                         });
                    </script>

is there any way fix it here instead of using new form submit event ?

That would be because the button click event occurs first, and only after that does the form onsubmit event get to validate the form.

yes but how to prevent it , I am confused

I recommend removing the button click event, and instead having the validation code trigger the ajax code when things correctly validate.

hey thanks for suggesstion but, I couldn’t understand it properly .

You need the validation function to execute the json submit code.

That can be done by moving the json submit function to a separate function, and then calling that function from the end of the validation code.

thanks this is much clear now and I have created two functions
one is validate and other is send
this is script for validate function

                                            <script>
                     
                             function validate(){

                              var name = $('#name').val();
                              var email = $('#email').val();
                              var mobile = $('#mobile').val();
                              var msg = $('#message').val();

                              $(".error").remove();

                              if (name.length < 1) {
                                $('#name').after('<span class="error">This field is required</span>');
                                 }

                                 if(email == "" ){
                                  $('#email').after('<span class="error">This field is required</span>');
                                   } 
                                  else if(email.indexOf('@') <= 0 ){
                                        
                                   $('#email').after('<span class="error">Enter a valid email</span>');
                                    }
                                   
                                 
                                  
                                   if (mobile == "") {
                                $('#mobile').after('<span class="error">This field is required</span>');
                                 }
                                 else if(mobile.length != 10) {
                                $('#mobile').after('<span class="error">Please enter valid mobile number. </span>');
                                 }else{
                                    //
                                 }


                                 if (msg.length < 1) {
                                $('#message').after('<span class="error">This field is required</span>');
                                 }

                            }

                        </script>       

This is my script for send function

                                       <script>
                        function send(){
                          var form_data = $('form').serialize(); // if(name && email && mobile && message ){
                           
                              if ($("#name").val() )
                                  {
                                       $.ajax({
                                               type: "post", 
                                                url: "email.php",
                                                dataType: "json", // Add datatype
                                                 data: form_data,
                                                   success: function () {
                                                    $('#thank_you').modal('show');
                                                      // window.location.href='#thank_you';   
                                                      }

                                               }); 
                                    document.getElementById("contact_form").reset();

                                  }
                                }
                       
                    </script>

this is how I am calling validate on clicking submit

                                 <button   type="submit" name="submit" onclick="return validate()" id="submit" class="btn submit-btn">Sign Up Now</button>

is this correct now ? now I am confused on how can I call send function ?

That is done from the end of the validation function.

ok that means just above tag I need to put the below line ?

                            return send();

is it correct?

It doesn’t even need to return.
It’s best to not use return when nothing is expected to return, as that can confuse about whether something really needs to be returned or not.

ok done with that but now after clicking submit it shows validation if the fields are empty and at same time the page is refreshing how to prevent this action can you check the above function once ?

When the validation fails, the form still attempts to submit. That’s because it’s trying to do the default action for a form.

You need to tell the form to stop attempting to do the default action. That’s where the preventDefault method is used.

To achieve that, the onsubmit attribute needs to give event to the validation function.
Then the validation function needs to have an event parameter, so that you can call event.preventDefault() before the return false lines.

hey thanks I fixed it now and its working properly but still there is problem with submit button

fyi-here sign up button is my submit button
Sign up button works only once… on 2nd request its do not works unless i refresh the page

1 Like

Does the browser console show any errors?

no it instead giving me my form data successfully because I print it, so its working properly but not submit button