WooCommerce: Maxlength and Minlength for Checkout Fields

If you’re familiar with HTML, you can add “maxlength” and “minlength” attributes to an input field in order to force its value to be min X and max Y characters long. This is all good and easy, so we might as well see what happens on the WooCommerce Checkout page once we apply such attributes to a given custom field.

Spoiler alert: maxlength works, while minlength does not. Hence, forcing a given checkout field to have a minimum length is actually quite impossible, unless we validate the posted data (a field input value that is not long enough) once the checkout is submitted. That’s a bummer, and in this article I will also explain how to contact WooCommerce so they can improve a functionality / fix a bug.

Enjoy!

Here’s what happens on the WooCommerce Checkout page after applying “Snippet 1” below: the company input field has a maxlength of 15 characters and it’s impossible to enter more than that.

PHP Snippet 1: Set Checkout Field “Maxlength”

In the example below, I’m forcing the “Company Name” field to have maximum 15 characters.

Once on the checkout page, you will see you cannot physically enter more than 15 characters inside that field. You can view the outcome in the screenshot above.

/**
 * @snippet       Maxlength @ WooCommerce Checkout Field
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 4.5
 * @community     https://businessbloomer.com/club/
 */

add_filter( 'woocommerce_checkout_fields', 'bbloomer_checkout_fields_custom_attributes', 9999 );

function bbloomer_checkout_fields_custom_attributes( $fields ) {
	$fields['billing']['billing_company']['maxlength'] = 15;
	return $fields;
}

PHP Snippet 2: Set Checkout Field “Minlength”

Here comes the other side of the medal. Forcing a minimum length on a checkout field is not possible. Here is all the stuff I tried (and blatantly failed), by using the same exact PHP of Snippet 1 above.

This first try does not work at all:

/**
 * @snippet       NOT WORKING: Minlength @ WooCommerce Checkout Field
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 4.5
 * @community     https://businessbloomer.com/club/
 */

add_filter( 'woocommerce_checkout_fields', 'bbloomer_checkout_fields_custom_attributes', 9999 );

function bbloomer_checkout_fields_custom_attributes( $fields ) {
	$fields['billing']['billing_company']['minlength'] = 15;
	return $fields;
}

This second attempt correctly adds the “minlength” attribute to the company field input, but nothing happens on the validation end i.e. you can submit the checkout and no error will be returned:

/**
 * @snippet       NOT WORKING: Minlength @ WooCommerce Checkout Field
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 4.5
 * @community     https://businessbloomer.com/club/
 */

add_filter( 'woocommerce_checkout_fields', 'bbloomer_checkout_fields_custom_attributes', 9999 );

function bbloomer_checkout_fields_custom_attributes( $fields ) {
	$fields['billing']['billing_company']['custom_attributes']['minlength'] = 15;
	return $fields;
}

Basically, the field won’t validate minlength even if the minlength attribute is there:

Despite the company field has a minlength attribute, the checkout process won’t stop on submit

The third attempt is another workaround given that minlength is not working. I tried to add a “pattern” attribute instead, which achieves the same thing (minimum 15 characters):

/**
 * @snippet       NOT WORKING: Minlength @ WooCommerce Checkout Field
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 4.5
 * @community     https://businessbloomer.com/club/
 */

add_filter( 'woocommerce_checkout_fields', 'bbloomer_checkout_fields_custom_attributes', 9999 );

function bbloomer_checkout_fields_custom_attributes( $fields ) {
	$fields['billing']['billing_company']['custom_attributes']['pattern'] = '.{15,}';
	return $fields;
}

Well, nothing is working and checkout still submits despite there is a field input error. So, no matter what we do, even if we set minlength attribute WooCommerce is not validating the checkout field input value. The only choice we have is to stop the checkout process unless a field input has 15 characters or more. I’ve achieved it this way:

/**
 * @snippet       WORKING: Minlength Validation @ WooCommerce Checkout Field
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 4.5
 * @community     https://businessbloomer.com/club/
 */

add_action( 'woocommerce_checkout_process', 'bbloomer_checkout_fields_custom_validation' );
  
function bbloomer_checkout_fields_custom_validation() { 
	if ( isset( $_POST['billing_company'] ) && ! empty( $_POST['billing_company'] ) ) {
		if ( strlen( $_POST['billing_company'] ) < 15 ) {
			wc_add_notice( 'Company name requires at least 15 characters', 'error' );
		}
	}	
}

And this is what happens once I enter a company name that is less than 15 characters and submit the checkout:

The checkout process stops because “Company name” has not enough characters (15).

This is great and it works, but if WooCommerce were able to handle minlength instead, there would be no problems whatsoever and I wouldn’t have the need to come up with a custom validation workaround to stop the checkout.

Pity, because WooCommerce “reads” maxlength, so I don’t see why it shouldn’t do the same with minlength and pattern. So, today, I’m going to show you how to let WooCommerce know there is a bug / functionality improvement that is worth bringing to the developers attention.

In order to do that I go to https://github.com/woocommerce/woocommerce/issues and do a quick search to see if any of the opened issues contains the word “minlength”:

Now that I know there is no duplicate issue, I can create a “new issue” (green button), enter a title and a good description: https://github.com/woocommerce/woocommerce/issues/27803

By doing so, I’ve requested an improvement and have not just complained about something that does not work or – even worse – said nothing. It’s an open source community and we’ve got to help each other.

You can follow WooCommerce developers opening, discussing and closing this “issue” at the same link.

Hope this will help someone.

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce: Cart and Checkout on the Same Page
    This is your ultimate guide – complete with shortcodes, snippets and workarounds – to completely skip the Cart page and have both cart table and checkout form on the same (Checkout) page. But first… why’d you want to do this? Well, if you sell high ticket products (i.e. on average, you sell no more than […]
  • WooCommerce: Disable Payment Method If Product Category @ Cart
    Today we take a look at the WooCommerce Checkout and specifically at how to disable a payment gateway (e.g. PayPal) if a specific product category is in the Cart. There are two tasks to code in this case: (1) based on all the products in the Cart, calculate the list of product categories in the […]
  • WooCommerce: Add Privacy Policy Checkbox @ Checkout
    Here’s a snippet regarding the checkout page. If you’ve been affected by GDPR, you will know you now need users to give you Privacy Policy consent. Or, you might need customer to acknowledge special shipping requirements for example. So, how do we display an additional tick box on the Checkout page (together with the existing […]
  • WooCommerce: Redirect to Custom Thank you Page
    How can you redirect customers to a beautifully looking, custom, thank you page? Thankfully you can add some PHP code to your functions.php or install a simple plugin and define a redirect to a custom WordPress page (as opposed to the default order-received endpoint). This is a great way for you to add specific up-sells, […]
  • WooCommerce: Disable Payment Gateway by Country
    You might want to disable PayPal for non-local customers or enable a specific gateway for only one country… Either way, this is a very common requirement for all of those who trade internationally. Here’s a simple snippet you can further customize to achieve your objective. Simply pick the payment gateway “slug” you want to disable/enable […]

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

8 thoughts on “WooCommerce: Maxlength and Minlength for Checkout Fields

  1. Hello

    Thank you for this tutorial very usefull.

    We have a module that forces in javascript in the checkout the max length to 35 characters on the address line. So if the customer’s address exceeds 35 characters, I would like to force the return on the second address line automatically. It often happens that customers type their address and do not pay attention that it is blocked at 35 characters and in the end have a cut address.

    Any clue would be help
    Thank you

    1. Hi Richard thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  2. It works great thanks alot bro

  3. Nice simple code to limit field character length.
    But is there a way to liited the combined value of First Name and Last Name?
    We dispatch those in our order details as Name but we need to also limt the length of these to 35 characters.

    1. Hi David, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

Your email address will not be published. Required fields are marked *