wordpress - Contact Form 7 Regular Expression Validation -
i'm trying add regular expression validation contact form 7 'last-name' field allow hyphenated names. have researched , written function allow this, doesn't seemed working. appreciated.
here function have written , placed in functions.php file...
add_filter('wpcf7_validate_text', 'custom_text_validation', 20, 2); add_filter('wpcf7_validate_text*', 'custom_text_validation', 20, 2); function custom_text_validation($result, $tag) { $type = $tag['type']; $name = $tag['name']; if($name == 'last-name') { $value = $_post[$name]; if(!preg_match('[a-za-z\-]', $value)){ $result->invalidate($tag, "invalid characters"); } } return $result; }
so first thing think need @ on 5th , 6th lines. according cf7 documentation, $tag
argument returns object , not array.
which means $tag['name']
, $tag['type']
should $tag->name
, $tag->type
.
the second thing address regex expression, time read on falsehoods programmers believe names. basically, in short, there lot of last names not match if criteria mixedalpha , dash.
if, however, intent on cutting out portion of potential users, might suggest making use maček's basic regex listed on this answer atleast include few more potential valid last names.
this turn function this:
add_filter('wpcf7_validate_text', 'custom_text_validation', 20, 2); add_filter('wpcf7_validate_text*', 'custom_text_validation', 20, 2); function custom_text_validation($result, $tag) { $type = $tag->type; //object instead of array $name = $tag->name; //object instead of array if($name == 'last-name') { $value = $_post[$name]; if(!preg_match("/^[a-z ,.'-]+$/i", $value )){ //new regex statement $result->invalidate($tag, "invalid characters"); } } return $result; }
Comments
Post a Comment