Skip to content Skip to sidebar Skip to footer

Validation Function For Add To Cart Form Submission

We've added some custom fields into the add to cart form within Shopify and are trying to add some validation. We've written our custom validation function and are trying to bind i

Solution 1:

I think you can do this by going old school javascript function.

functioncheckForm() {       
   //What ever you want to checkconsole.log("Validation called");
   returnfalse;
}

and in the form call the function with return

<form id="AddToCartForm" action="" onsubmit="return checkForm()">
..
</form>

Solution 2:

Something appears to be wrong with your form fields and the functions assigned. Here is the shortened version.

$(function(){
  $('form').on('submit',function() {
    var formIsValid = true;
    var message = "Please fill this out and you will be able to add the item to your cart.";
    $(this).find('[name^="properties"]').filter('.required, [required="required"]').each(function() { // Filter appears to be wrong here. Since you are going with manual form validation, use class="required" instead of attribute "required" in form HTML
      $(this).removeClass('error');
      if (formIsValid && $(this).val() == '') {
        formIsValid = false;
        message = $(this).attr('data-error') || message;
        $(this).addClass('error');
      }
    });
    if (!formIsValid) alert(message)
    return formIsValid
  }).find('input, select, textarea').focus(function() {
    $(this).removeClass('error');
  });
})

Try it out: https://jsfiddle.net/xewsw2t8/8/

Solution 3:

Shopify does indeed override all form submission events, which is extremely frustrating. I ended up trying to trace the contact form (simplest one) to find out where these mysterious AJAX calls were coming from that were bullying my on submit code. Turns out they come from the app.js.liquid file. Here's the contact form example:

var$notify_form = $('.notify_form .contact-form');
  $notify_form.each(function() {
    var$nf = $(this);
    $nf.on("submit", function (e) {
      if($nf.find('.notify_email').val() != "") {
        $.ajax({
            type: $nf.attr('method'),
            url: $nf.attr('action'),
            data: $nf.serialize(),
            success: function (data) {
              $notify_form.fadeOut("slow", function(){
                $nf.prev('.message').html({{ 'products.notify_form.post_success' | t | json }});
              });
            }
        });
      } else {
        $nf.prev('.message').html({{ 'products.notify_form.post_error' | t | json }});
      }  
      e.preventDefault();
    });
  });

Following the precise structure above led me to a working solution for my form validation. Hope this helps out!

Post a Comment for "Validation Function For Add To Cart Form Submission"