WordPress.org

Forums

Contact Form 7
Number / Phone Validation for Contact Form 7 - Doing it Manually (7 posts)

  1. codinedawn
    Member
    Posted 9 months ago #

    After much reading, I've found a way to validate a CF7 textfield for "numbers only".

    One doesn't have to hack the plugin source files to achieve this, which is good.

    You will have to edit the function code to suit your needs.

    Always test locally, not on a live website.

    Step one:
    Add this code to your theme's function.php (wp-content/themes/your-theme/functions.php)

    /*
    Validate Numbers in Contact Form 7
    This is for 10 digit numbers
    */
    
    function is_number( $result, $tag ) {
    $type = $tag['type'];
    $name = $tag['name'];
    
    if ($name == 'phone' || $name == 'fax') { // Validation applies to these textfield names. Add more with || inbetween
    $stripped = preg_replace( '/\D/', '', $_POST[$name] );
    $_POST[$name] = $stripped;
    if( strlen( $_POST[$name] ) != 10 ) { // Number string must equal this
    $result['valid'] = false;
    $result['reason'][$name] = $_POST[$name] = 'Please enter a 10 digit phone number.';
    }
    }
    return $result;
    }
    
    add_filter( 'wpcf7_validate_text', 'is_number', 10, 2 );
    add_filter( 'wpcf7_validate_text*', 'is_number', 10, 2 );

    Step 2:
    Create 2 normal, required textfields with the name 'phone' and 'fax' in your CF7 form. Example:

    <p>Phone Number:<br />
    [text* phone] </p>
    
    <p>Fax Number:<br />
    [text* fax] </p>

    That's it, not very refined but works for me.

    http://wordpress.org/extend/plugins/contact-form-7/

  2. biswajeet
    Member
    Posted 9 months ago #

    Thanks, will check it...

  3. Henry Gunawan
    Member
    Posted 4 months ago #

    I've tried that and it works great. But it replaces the current wpcf7_text_validation_filter, isn't it?

  4. dstZloi
    Member
    Posted 4 months ago #

    Thank you very much! Works for me.

  5. peterhadorn
    Member
    Posted 4 months ago #

    Thanks a lot, works like a breeze :)

  6. christineeverth
    Member
    Posted 2 months ago #

    Worked! So easy. Thanks a lot.

  7. nishavnvn
    Member
    Posted 11 hours ago #

    Its really awesome, i was meaninglessly trying different ways but this only post worked magical for me.

    Thankyou so much.

Reply

You must log in to post.

About this Plugin

About this Topic