54

JavaScript bit:

$(document).ready(function()
    {
            $('#form').submit(function(e)
            {     

                e.preventDefault();
                var $form = $(this);

                // check if the input is valid
                if(! $form.valid()) return false;
                    $.ajax(
                    {
                    type:'POST',
                    url:'add.php',
                    data:$('#form').serialize(),
                    success:function(response)
                    {
                        $("#answers").html(response);
                    }
                });     

            })
    });

HTML bit:

    <input type="text" name="answer[1]" class="required" />
    <input type="text" name="answer[2]" class="required" />

So this is the code I am trying to use. The idea is to get all my inputs validated before I send my form with Ajax. I've tried numerous versions of this now but every time I end up with submitting even though the form is not entirely filled out. All my inputs are of the "required" class. Can anyone see what I am doing wrong?

Also, I depend on class-based requirements as my input names are generated with php so I can never be sure what name[id] or input types I get.

I show/hide questions as I go through it in "pages".

<input type="button" id="next" onClick="toggleVisibility('form3')" class="next-btn"/>

JS:

function toggleVisibility(newSection) 
        {
            $(".section").not("#" + newSection).hide();
            $("#" + newSection).show();
        } 
4
  • What happens when you submit? Commented Jul 13, 2012 at 11:31
  • At the moment I just echo out all the $key => $value pairs and they keep popping up on my screen even if I only fill out 1/4 questions. Commented Jul 13, 2012 at 11:32
  • I couldn't find beforeSubmit as a valid option for $.ajax in the latest version of jquery (v1.7.2). You may want to use the latest version of jquery. That said, Darin's answer is how it ought to be done. That said, if you just can't do what he is suggesting, then replace the last line of your beforeSubmit with the code Fliespl has put up. You need to check the return value of .validate() and accordingly either proceed with or cancel ajax request. Commented Jul 13, 2012 at 11:43
  • Trying the fliespl lines but it still just submits. Updated code in question. Commented Jul 13, 2012 at 12:31

15 Answers 15

116

You could use the submitHandler option. Basically put the $.ajax call inside this handler, i.e. invert it with the validation setup logic.

$('#form').validate({

    ... your validation rules come here,

    submitHandler: function(form) {
        $.ajax({
            url: form.action,
            type: form.method,
            data: $(form).serialize(),
            success: function(response) {
                $('#answers').html(response);
            }            
        });
    }
});

The jQuery.validate plugin will invoke the submit handler if the validation has passed.

Sign up to request clarification or add additional context in comments.

6 Comments

But I can still serialize #answers before I validate or stick it right before $.ajax ?
#answers is your result div. If you want to send the form input field values along with the AJAX request, use the .serialize() method, exactly as shown in my answer: data: $(form).serialize() => inside the submit handler.
Do you think there's any chance that splitting up the form in several divs that are hidden/shown as the user goes through the form could have anything to do with me not getting this code to work?
Right on target as always, +1
Right on target² hahah +1
|
22

first you don't need to add the classRules explicitly since required is automatically detected by the jquery.validate plugin. so you can use this code :

  1. on form submit , you prevent the default behavior
  2. if the form is Invalid stop the execution.
  3. else if valid send the ajax request.
$('#form').submit(function (e) {
  e.preventDefault();
  var $form = $(this);

  // check if the input is valid using a 'valid' property
  if (!$form.valid) return false;

  $.ajax({
    type: 'POST',
    url: 'add.php',
    data: $('#form').serialize(),
    success: function (response) {
      $('#answers').html(response);
    },
  });
});

8 Comments

check if there an error in your browser log, what browser you use ?
I am using Google Chrome, but I can't find any errors there. Gonna try with this code once more.
Won't submit at all now, this goes into the $(document).ready(function(){ right?
yes it should be in the document ready block, have you added an ID to your form ?, your form must have <form id='form'>... <input type=submit value=submit></form>
Now I am getting somewhere. I only had a input type="button". Still it only requires my checkboxes. It ignores the textboxes and radiobuttons. Could it be because they are hidden? I hide older questions and only present the current "page"
|
7

You can try doing:

if($("#form").validate()) {
 return true;
} else {
 return false;
}

1 Comment

I do change display: none on my form as I go dividing it up into several "pages". Think that could cause some problems?
7
> Required JS for jquery form validation
> ## jquery-1.7.1.min.js ##
> ## jquery.validate.min.js ##
> ## jquery.form.js ##

$("form#data").validate({
    rules: {
        first: {
                required: true,
            },
        middle: {
            required: true,
        },          
        image: {
            required: true,
        },
    },
    messages: {
        first: {
                required: "Please enter first",
            },
        middle: {
            required: "Please enter middle",
        },          
        image: {
            required: "Please Select logo",
        },
    },
    submitHandler: function(form) {
        var formData = new FormData($("#image")[0]);
        $(form).ajaxSubmit({
            url:"action.php",
            type:"post",
            success: function(data,status){
              alert(data);
            }
        });
    }
});

2 Comments

This answer is quite clearly explained for beginers... Thanks! But is this also validate the file attachment !! How !!
Does jquery.form.js required?
5

This specific example will just check for inputs but you could tweak it however, Add something like this to your .ajax function:

beforeSend: function() {                    
    $empty = $('form#yourForm').find("input").filter(function() {
        return this.value === "";
    });
    if($empty.length) {
        alert('You must fill out all fields in order to submit a change');
        return false;
    }else{
        return true;
    };
},

Comments

4

I think submitHandler with jquery validation is good solution. Please get idea from this code. Inspired from @Darin Dimitrov

$('.calculate').validate({

                submitHandler: function(form) {
                    $.ajax({
                        url: 'response.php',
                        type: 'POST',
                        data: $(form).serialize(),
                        success: function(response) {
                            $('#'+form.id+' .ht-response-data').html(response);
                        }            
                    });
                }
            });

Comments

3

I think that i first validate form and if validation will pass, than i would make ajax post. Dont forget to add "return false" at the end of the script.

Comments

0
function validateForm()
{
    var a=document.forms["Form"]["firstname"].value;
    var b=document.forms["Form"]["midname"].value;
    var c=document.forms["Form"]["lastname"].value;
    var d=document.forms["Form"]["tribe"].value;
    if (a==null || a=="",b==null || b=="",c==null || c=="",d==null || d=="")
    {
        alert("Please Fill All Required Field");
        return false;
    }
    else{

        $.ajax({
        type: 'post',
        url: 'add.php',
        data: $('form').serialize(),
        success: function () {
          alert('Patient added');
          document.getElementById("form").reset();
        }
      });

    }
}

  $(function () {

    $('form').on('submit', function (e) {
      e.preventDefault();

      validateForm();


    });
  });

3 Comments

did it like this
Welcome to Stack Overflow! Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.
why to use comparison operators? can't we use form.valid() ?? that would be more efficient.
0

You need to trigger form validation before checking if it is valid. Field validation runs after you enter data in each field. Form validation is triggered by the submit event but at the document level. So your event handler is being triggered before jquery validates the whole form. But fret not, there's a simple solution to all of this.

You should validate the form:

if ($(this).validate().form()) {
  // do ajax stuff
}

https://jqueryvalidation.org/Validator.form/#validator-form()

Comments

0
$("#myformId").submit(function (event) {
    // submit modal form of create & edit 
    event.preventDefault();
    formObj = $(this);
        
    // check the form input is valid or not if not valid then return false;
    if (!formObj.validate().form()) return false;

    data = $(formObj).serializeArray();

    // do stuff with ajax or anything else what you wants 
});

explainantion:- first validate form and if validation will pass, then call ajax request otherwise stop execution using return false;

var validator = $( "#myform" ).validate(); Validates the form, returns true if it is valid, false otherwise. So, we need to check just if (!formObj.validate().form())

for more details see here documentation

I share customization option of validate function

$(function () {
    $('form.needs-validation').each(function() {   // <- selects every <form> on page which contains .needs-validation class
        var validator = $(this).validate({
            errorElement: 'span',
            errorPlacement: function (error, element) {
                error.addClass('invalid-feedback');
                element.closest('.form-group').append(error);
            },
            highlight: function (element, errorClass, validClass) {
                $(element).addClass('is-invalid');
            },
            unhighlight: function (element, errorClass, validClass) {
                $(element).removeClass('is-invalid');
            }
        });
    });
});

for more details about to customize the JQuery validation see here

for Customizing the default Validation Messages see below answers URLs that was really helpful to me

  1. change default error message
  2. How do I include the field label in a JQuery Validate error message

Comments

0

HTML Form:

<div class="w3-padding w3-flat-clouds">
         <p><label>Your Name:</label><input id = 'name' class="w3-input w3-border" type="text" name = 'enter-name' placeholder = "Enter your Name" required></p>
         <p><label>Your Email:</label><input id = 'e-mail' class="w3-input w3-border" type="text" name = 'enter-email' placeholder = "Enter your email" required></p>
         <p><label>Your Message:</label><textarea id = 'message' style = 'height: 80px;' class="w3-input w3-border" name = 'enter-message' placeholder = "Enter your message..." required></textarea></p>
         <button class = 'w3-button w3-btn w3-black w3-hover-green' id = 'sub-btn'>submit</button>
      </div>

AJAX:

   $(document).ready(() => {
        $('#sub-btn').click(() => {
            var nameInsert = document.getElementById('name').value;
            var emailInsert = document.getElementById('e-mail').value;
            var messageInsert = document.getElementById('message').value;

            var atTheRate = emailInsert.indexOf("@");
            var dotPosition = emailInsert.lastIndexOf(".");
            if(atTheRate < 1 || dotPosition < 6)
            {
              alert(nameInsert + ' Please Provide Your Proper Email!');
              return false;      //Prevents your form to being submit.
            }
            else
            {
            $.ajax({  
                url: '/send-details',
                method: 'GET',
                data: {
                    nameInsert: nameInsert,
                    emailInsert: emailInsert,
                    messageInsert: messageInsert
                },
                success: (successObj) => {
                  var successResult = JSON.parse(successObj);
                    if(successResult)
                    {
                        console.log(successResult);
                        alert('Thank You ' + nameInsert + '! Your Message Received Successfully!');
                    }
                    else
                    {
                        console.log('Message Insertion failed!');
                        alert('Message Insertion failed!');
                    }
                }
            });
            return true;    //Allows you to submit.
          }
        });
   });

1 Comment

Please add some explanation to your answer.
0

If used «jquery-validate» validation plugin, then you need to understand a few details.

1. Form events that the plugin subscribes to are «click», «focusin», «focusout», «keyup», «submit». That is, he monitors the form - and, accordingly, the event «submit». Therefore, the plugin monitors the form in any case, there is no point in writing additional scripts.

2. The plugin cannot be initialized if the Form is loaded via ajax, i.e. at the time of initialization there is no DOM of the form yet. So a simple solution is to put the initialization in the event «click».

$(document).on('click','.cart-wrapper', function(){
  $('.cart-checkout-form').validate({
        rules: {
            name: {
                required: true,
                minlength: 2
            },
            phone: {
                required: true,
                minlength: 10
            },
            checkbox: {
                required: true
            },
    
        },
        messages: {
            name: {
                required: "Enter your name",
                minlength: "Your name must have at least 2 characters."
            },
            phone: {
                required: "Enter your phone",
                minlength: "Your name must have at least 10 characters."
            },
            checkbox: {
                required: "Required",
            },
    
        },
    
    });
});
.form-control {
  display: flex;
  margin-bottom: 5px;
}
#name-error, #phone-error {
  color: #ff0d00;
  margin-left: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/5.0.5/jquery.inputmask.min.js"></script>

<div class="cart-wrapper">
<form class="cart-checkout-form">
  <div class="form-control">
        <input type="text"
                name="name" 
                placeholder="Name" 
                value=""
                required />
  </div>
  <div class="form-control">
        <input type="text"
                name="phone" 
                value="" 
                placeholder="+7(___)___-__-__"
                required />
   </div>
   <div class="form-control">
        <input type="checkbox"
                name="checkbox" 
                required />
   </div>

        <input type="submit" value="Checkout">
</form>
</div>

Comments

0
            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>
          <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
        
         <meta name="csrf-token" content="{{ csrf_token() }}" />
           var web_url = "{{ url('/') }}";
                var token = $('meta[name="csrf-token"]').attr("content");
                $.validator.setDefaults({
                    ignore: ":hidden, [contenteditable='true']:not([name])"
                });
        
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });
        
           {{ Form::open(['route' => ['admin.menus.store'],'id' => 'menu_form', 'method'=>'post']) }}
              {{ Form::close() }}
        
               $("#menu_form").validate({
  rules: {
    class_name: {
      required: true,
    },
    name: {
      required: true,
    },
    icon: {
      required: true,
    },
  },
  messages: {
    class_name: {
      required: "Class Name is required",
    },
    name: {
      required: "Name is required",
    },
    icon: {
      required: "Icon is required",
    },
  },
  errorPlacement: function (error, element) {
    error.insertAfter(element);
  },
  submitHandler: function (form) {
    var form_data = $("#menu_form").serialize();
    $("#addaddmenu").prop("disabled", true);
        $.ajax({
        url: "{{ route('admin.menus.store') }}",
        type: "POST",
        dataType: "json",
        data: form_data,
        statusCode: {
                200: function (xhr) {
                $.toast({
                    heading: "success",
                    text: xhr.data.message,
                    position: "top-right",
                    icon: "success",
                    position: {
                    right: 10,
                    top: 90,
                    },
                });
                window.location.href = "{{ route('admin.menus') }}";
                },
                422: function (xhr) {
                var result = xhr.responseJSON.error.filter((obj) => {
                    // if( $(`input[name="${obj.name}"]`).val() == "" || ){
                    $.each(
                    xhr.responseJSON.error,
                    function (indexInArray, valueOfElement) {
                        $.toast({
                        heading: "success",
                        text: valueOfElement.message,
                        position: "top-right",
                        icon: "success",
                        position: {
                            right: 10,
                            top: 90,
                        },
                        });
                    }
                    );
                    // }
                });
                },
        },
        });
     },
});

    
    
    
//controller
public function validationMessage($validationObj)
{
    $response = [];
    foreach ($validationObj as $key => $value) {
        $obj = new \stdClass();
        $obj->name = $key;
        $obj->message = $value[0];

        array_push($response, $obj);
    }

    return $response;
}
    
         $validator = Validator::make($request->all(),[
                        'class_name' => ['required'],
                        'name' => ['required'],
                        'icon' => ['required'],
                    ]);
                    if($validator->fails()){
                        return response()->json(['success' => false, "error" => $this->validationMessage($validator->errors()->toArray())], 422);
            
         $data = new AdminMenu();
         $data->save();
         return response()->json(['success' => true, 'data' => ['message' => 'Menu successfully created.']], 200);
    
      

Comments

0
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-toast-plugin/1.3.2/jquery.toast.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-toast-plugin/1.3.2/jquery.toast.css" />    

  <meta name="csrf-token" content="{{ csrf_token() }}">

        var url = '{{ url('/') }}';
          $("#create_content").validate({
                    rules: {
                        name: { required: true },
                        email: { required: true, email: true },
                    },
                    messages: {
                        name: { required: "The name field is required." },
                        email: { required: "The email field is required." },
                    },
                    errorElement: 'span',
                    errorPlacement: function(error, element) {
                        error.addClass('invalid-feedback');
                        element.closest('.elem').append(error);
                    },
                    highlight: function(element, errorClass, validClass) {
                        $(element).addClass('is-invalid');
                    },
                    unhighlight: function(element, errorClass, validClass) {
                        $(element).removeClass('is-invalid');
                    },
                     submitHandler: function(form) {
                        $.ajaxSetup({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            }
                        });
                        var form = $('#create_content')[0];
                        var data = new FormData(form);
                        $.ajax({
                            url: url + '/contact-us/store',
                            type: "POST",
                            data: data,
                            processData: false,
                            contentType: false,
                            statusCode: {
                                200: function(xhr) {
                                 $.toast({
                                            heading: "success",
                                            text: xhr.data.message,
                                            position: "top-right",
                                            icon: "success",
                                            position: {
                                                right: 10,
                                                top: 90,
                                        },
                                    });
                                    window.location.href = url + "/contact-us"; 
                                    $("#submit_btn").attr("disabled", false);
                                },
                                422: function(xhr) {
                                    var result = xhr.responseJSON.error.filter(obj => {
                                            // if( $(`input[name="${obj.name}"]`).val() == "" || ){
                                            $.each(xhr.responseJSON.error, function (indexInArray, valueOfElement) { 
                                                $.toast({
                                                        heading: "success",
                                                        text: valueOfElement.message,
                                                        position: "top-right",
                                                        icon: "success",
                                                        position: {
                                                            right: 10,
                                                            top: 90,
                                                    },
                                                });
                                            });
                                        // }
                                    })
                                }
                            }
                        });
                    }
                });

Comments

-1

Form native JavaScript checkValidity function is more then enough to trigger the HTML5 validation

$(document).ready(function() {
    $('#urlSubmit').click(function() {
        if($('#urlForm')[0].checkValidity()) {
            alert("form submitting");
        }
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.