Home / Archive / Require Us Phone Number Format
Duplicate Snippet

Embed Snippet on Your Site

Require Us Phone Number Format

This snippet shows how to alter the phone field so that it only accepts a number between 8 and 12 digits long, with an optional + at the start.

Code Preview
php
<?php
/**
 * This snippet shows how to alter the phone field so
 * that it only accepts a number between 8 and 12 digits
 * long, with an optional + at the start.
 *
 * However, this example more generally shows how you can
 * force a field value to match a certain regex pattern.
 *
 * @param  array $fields The fields in the form.
 * @return array
 */
function ed_require_us_phone_format( $fields ) {
	/* If a phone field doesn't exist, stop right here. */
	if ( ! array_key_exists( 'phone', $fields ) ) {
		return $fields;
	}
	/* Make sure that 'attrs' exists in the field. */
	if ( ! array_key_exists( 'attrs', $fields['phone'] ) ) {
		$fields['phone']['attrs'] = [];
	}
	/**
	 * This defines the format of the phone number as being a
	 * string of 3 numbers, followed by a dash, then 3 more numbers,
	 * than 4 more numbers. US phone format, required by Authorize.Net.
	 */
	$pattern = '+?[0-9]{3}-[0-9]{3}-[0-9]{4}';
	/**
	 * Add the pattern to the field by adding it to the
	 * `attrs` array.
	 */
	$fields['phone']['attrs']['pattern'] = $pattern;
	$fields['phone']['help'] = 'Please enter a phone number formatted like 111-111-1111.';
	return $fields;
}
add_filter( 'charitable_donation_form_user_fields', 'ed_require_us_phone_format' );
add_filter( 'charitable_user_address_fields', 'ed_require_us_phone_format' );
add_filter( 'charitable_campaign_submission_user_fields', 'ed_require_us_phone_format' );

Comments

Add a Comment