【问题标题】:Validation function for add to cart form submission添加到购物车表单提交的验证功能
【发布时间】:2016-07-14 04:24:25
【问题描述】:

我们已在 Shopify 的“添加到购物车”表单中添加了一些自定义字段,并正在尝试添加一些验证。我们已经编写了自定义验证函数,并尝试使用以下代码绑定它,我们将其放置在 body 标签内的 theme.liquid 中:

jQuery(function($) {
  $('#AddToCartForm').submit(function() {
      console.log("Validation called");
      return false;
  });
});

我们修改了“添加到购物车”表单,使其具有 AddToCartForm id。但是,永远不会调用此函数。仅记录 $('#AddToCartForm') 表明选择器工作正常。我们还尝试将其移至产品液体页面,使其位于表单关闭标签下方,但这并没有改变任何东西。我们还尝试绑定到提交按钮本身,然后使用

e.preventDefault();
e.stopPropagation();

阻止表单提交,但这也不起作用。但是,它确实绑定并且函数被正确调用,它只是不会停止提交。我们整天都在尝试解决这个问题,并且完全没有想法,非常感谢任何帮助。

编辑:

我们其实也尝试过使用onSubmit,所以代码是:

<form onSubmit='return test()'>

js 是:

function test() {
  console.log("Validation called");
  return false;
}

这个函数也从未被调用过。

我们尝试的另一件事是将添加到购物车按钮更改为:

<button type="button" name="add" id="AddToCart" class="btn">

来自

<button type="submit" name="add" id="AddToCart" class="btn">

然后调用 $('#AddToCartForm').submit() 如果验证通过,主要问题是有人可以从控制台调用 $('#AddToCartForm').submit() 来提交表单并绕过所有验证..

我们当前的验证脚本是:

jQuery(function($) {
  $('#AddToCart').click(function(e) { //Changed this to the ID of the submit button and changed .submit to .click
    console.log(e);
    e.preventDefault();
    e.stopPropagation();
    var formIsValid = true;
    var message = "Please fill this out and you will be able to add the item to your cart.";
    /* Changed this to the ID of the form itself */ $('#AddToCartForm').find('[name^="properties"]').filter('.required, [required="required"]').each(function() {
      $(this).removeClass('error');
      if (formIsValid && $(this).val() == '') {
        formIsValid = false;
        message = $(this).attr('data-error') || message;
        $(this).addClass('error');
      }
    });
    if (formIsValid){
      $('#AddToCartForm').submit();
      return true;
    }
    else {
      alert(message);
      return false;
    }
  }).find('input, select, textarea').focus(function() {
    $(this).removeClass('error');
  });
});

它基于:https://help.shopify.com/themes/customization/products/get-customization-information-for-products#require-fieldshttps://gist.github.com/carolineschnapp/11167400

shopify 表单的 HTML 是:

<form action="/cart/add" method="post" enctype="multipart/form-data" id="AddToCartForm">
  <select name="id" id="productSelect" class="product-single__variants">
    {% for variant in product.variants %}
    <option {% unless variant.available %} disabled="disabled" {% endunless %} {% if variant == current_variant %} selected="selected" {% endif %} data-sku="{{ variant.sku }}" value="{{ variant.id }}">{{ variant.title }} - {% if variant.available %}{{ variant.price | money_with_currency }}{% else %}{{ 'products.product.sold_out' | t }}{% endif %}</option>
    {% endfor %}
  </select>

  <div class="product-single__quantity{% unless settings.product_quantity_enable %} is-hidden{% endunless %}">
    <label for="Quantity">{{ 'products.product.quantity' | t }}</label>
    <input type="number" id="Quantity" name="quantity" value="1" min="1" class="quantity-selector">
  </div>

  <button type="submit" name="add" id="AddToCart" class="btn">
    <span id="AddToCartText">{{ 'products.product.add_to_cart' | t }}</span>
    </button>
</form>

【问题讨论】:

  • 将“提交”更改为“按钮”并使用.on('click',function()...。验证后使用$('#form_id').submit().
  • 这行得通,但它不再是像以前添加到购物车那样的 AJAX 调用。知道为什么吗?
  • 最重要的是,不幸的是有人可以在控制台中输入 $('AddToCartForm').submit() 来绕过验证,关于如何解决这个问题的任何想法?
  • 可以分享完整的表单代码和完整的验证功能吗?
  • 我已将其添加到原帖中

标签: javascript jquery shopify


【解决方案1】:

我认为你可以通过使用老式 javascript 函数来做到这一点。

function checkForm() {       
   //What ever you want to check
   console.log("Validation called");
   return false;
}

并在表单中使用 return 调用函数

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

【讨论】:

  • 我实际上只是编辑了我的原始帖子以包含我们尝试过的内容。不幸的是,它也没有用。该函数从未被调用过。
  • (function(){ // 你的 JavaScript 在这里 function checkForm() { // 你想检查什么 console.log("Validation called"); return false; } })();试试这个。
  • jQuery(function($) { function test() { console.log("call"); return false; } });还是失败了。 (function(){ function checkForm() { console.log("验证调用"); return false; } })();也失败了。我确实两次都使用正确的函数名称更新了 onSubmit。
  • 不带 jQuery 标记试试吧.. (function(){ // 你的 JavaScript 在这里 function checkForm() { // 你想检查什么 console.log("Validation called"); return假;}})();
  • 在没有 jQuery 标签的情况下也试过了。仍然没有工作。 :( 我使用的代码是: (function(){ function checkForm() { console.log("Validation called"); return false; } })();
【解决方案2】:

您的表单域和分配的功能似乎有问题。这是缩短版。

$(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');
  });
})

试试看:https://jsfiddle.net/xewsw2t8/8/

【讨论】:

  • 我已将 shopify 中表单的 html 添加到原始帖子中。复制粘贴您的确切代码并在函数前面添加一个 console.log 以显示它被调用,但它从未被调用..
  • 该表单对我来说很好用。还有别的问题。能否分享实时页面链接,以便我自己查看?
  • 您是否在 shopify 中尝试过?这是未对表单的 HTML 进行自定义的基本产品:haris-test-shop.myshopify.com/products/test 这是对表单进行 HTML 自定义的产品:haris-test-shop.myshopify.com/products/hari-test-product 商店的密码是:schait
  • 正如预期的那样,分配给购物车提交的另一个函数覆盖了此函数。让我看看能做些什么。
【解决方案3】:

Shopify 确实会覆盖所有表单提交事件,这非常令人沮丧。我最终试图追踪联系表格(最简单的一个),以找出这些神秘的 AJAX 调用来自哪里,它们欺负了我的提交代码。原来它们来自 app.js.liquid 文件。以下是联系表格示例:

  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();
    });
  });

按照上面的精确结构,我找到了一个有效的表单验证解决方案。希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 2021-03-12
    相关资源
    最近更新 更多