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>
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;
}
Thanks @or-assayag but that seems to prevent spaces being entered completely. i want to allow users to be able to enter spaces between words, but not just enter a space as the only character in the text box.
Hey, updated my answer, hopefully it will work.
Thank you @or-assayag. That should work fine
Good to hear. glad to help, please upvote and mark answer as accepted. Thanks and good luck :)
Thanks. One last question. In order to display a dialog box message to the user when they have only entered a space in the textbox is the following correct:
code
function validate() { var text = document.getElementById("Line 1-0-0").value; if (!text.replace(/\s/g, '').length) { alert ( "This line cannot be left blank"); return false; } return true; }