Contact Form 7 Name validation (catch all special characters except whitespace)

Viewed 12

This is not a question, just a fellow wordpress developer contributing to the community. I have tried so many things but only this worked. /[\W]/ catches whitespaces also so i couldnt figure out a turnaround. Hope this helps someone atleast.

add_filter( 'wpcf7_validate_text', 'wpcs_custom_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_text*', 'wpcs_custom_validation_filter', 10, 2 );

function wpcs_custom_validation_filter( $result, $tag ) {
    $name = $tag->name;

    $value = isset( $_POST[$name] )
        ? trim( wp_unslash( strtr( (string) $_POST[$name], "\n", " " ) ) )
        : '';

    if ( 'text' == $tag->basetype ) {
        if ( preg_match('/[.|0-9|{|}|;|\'|!|@|#|$|%|^|&|(|)|_|\-|\+|*|?|<|>|~]/', $value ) ) {
            $result->invalidate( $tag, 'Please enter only text characters.' );
//$result->invalidate( $tag, wpcf7_get_message( 'invalid_wpcs_custom_error' ) );
        }
    }
    return $result;
}
0 Answers
Related