Warm tip: This article is reproduced from serverfault.com, please click

How to prevent entering space only in a text field on Shopify website

发布于 2020-11-28 20:33:00

I have input text boxes on my website to allow products to be personalised.

The fields must contain some text but some customers workaround this by just entering a space and submitting the form. This is a problem as the personalisation can't be left blank and has to be some text value, even if it's just a dot or a hyphen, for example.

How do I prevent the form being submitted where the text box only has a single space as the only character that has been entered?

The code is Liquid as it's a Shopify e-commerce store

    <div class="personalisation_label">
    <p>Type the personalisation you want below:</p>
    </div>
    <div class="personalisation">
    <input type="text" name="properties[Line 1]" id="Line 1-0-0" maxlength="12" size="12">
    <button type="submit" name="add" id="AddToCart" class="btn {{ btn_class }}{% if section.settings.enable_payment_button %} btn--secondary{% endif %}">
    <span id="AddToCartText">{{ 'products.product.add_to_cart' | t }}</span>
    </button>
    </div>
Questioner
masted75
Viewed
0
Or Assayag 2020-11-30 00:29:00

HTML:

<button type="submit" name="add" id="AddToCart" onclick="return validate();" ... rest of the HTML

JavaScript:

function validate() {
   var text = document.getElementById("Line 1-0-0").value;
   if (!text.replace(/\s/g, '').length) {
       return false;
   }
   return true;
}