Home / Archive / MemberPress: Limit Phone Number Digits
Duplicate Snippet

Embed Snippet on Your Site

MemberPress: Limit Phone Number Digits

This code snippet limits the number of digits users can enter into a custom phone number field on MemberPress registration forms. If the number of digits does not match the set limit, the user will be prevented from submitting the registration form, and the error message will be displayed.

The sample code requires 11 digits to be added to the custom phone number field. Accordingly, it will display the "Phone number must be 11 digits." message if a different number of digits is added to the field.

The sample code uses the mepr_phone_number slug for the custom phone number field. This slug should match the slug of the phone custom field used in the registration form to collect the phone number. Thus, if the phone number filed has a different slug, it should be replaced on the following lines:

$phone = isset( $_POST['mepr_phone_number'] ) ?

and

sanitize_text_field(trim($_POST['mepr_phone_number'])) : '';

Further, the set limit requiring the exact number of 11 digits (11) can be adjusted on the following line: 

    if (strlen($phone) != 11) {

The limit can be set to any whole number above 0 (zero) to require the exact number of phone number digits. It can also contain the more (>) or less (<) symbol in front of the number to set the minimum or the maximum of the required digits.

To modify the error message, edit the  text on the following line:

$errors['invalid_phone'] = 'Phone number must be 11 digits.';

Code Preview
php
<?php
function mepr_limit_phone_digits( $errors ) {
    $phone = isset( $_POST['mepr_phone_number'] ) ? sanitize_text_field(trim($_POST['mepr_phone_number'])) : '';
    // Remove all non-numeric characters from the phone number.
    $phone = preg_replace("/[^0-9]/", "", $phone);
    // Check if phone digits equal 11
    if (strlen($phone) != 11) {
        $errors['invalid_phone'] = 'Phone number must be 11 digits.';
    }
    return $errors;
}
add_filter('mepr-validate-signup', 'mepr_limit_phone_digits', 10, 1);

Comments

Add a Comment