WordPress.org

Ready to get started?Download WordPress

Forums

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

  1. codinedawn
    Member
    Posted 1 year 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 1 year ago #

    Thanks, will check it...

  3. Henry Gunawan
    Member
    Posted 1 year ago #

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

  4. Vlad
    Member
    Posted 1 year ago #

    Thank you very much! Works for me.

  5. peterhadorn
    Member
    Posted 1 year ago #

    Thanks a lot, works like a breeze :)

  6. christineeverth
    Member
    Posted 1 year ago #

    Worked! So easy. Thanks a lot.

  7. nishavnvn
    Member
    Posted 1 year ago #

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

    Thankyou so much.

  8. Dinesh Karki
    Member
    Posted 1 year ago #

    Have you used this plugin. It can add jquery validation to your contact form 7. Jquery validation are more quick and interactive.

    http://wordpress.org/plugins/jquery-validation-for-contact-form-7/

  9. codinedawn
    Member
    Posted 1 year ago #

    Thanks Dinesh, I'll test out your plugin on a new site I'm working on.

Topic Closed

This topic has been closed to new replies.

About this Plugin

About this Topic