I want to use the gform_field_validation function from Gravity Forms to validate a Full Name field only if there's a space between the two names, validating that someone didn't just put in one name, and put it a first and last name.
I believe I've found the correct Regex to do it /^[a-zA-Z ]+$/ . Just don't know how to implement it.
Try this:
add_filter( 'gform_field_validation', 'validate_fullname', 10, 4 );
function validate_fullname( $result, $value, $form, $field ) {
$pattern = "/^\w+\s\w+$/";
if ( ! preg_match( $pattern, $value ) ) {
$result['is_valid'] = false;
$result['message'] = 'Please enter a valid full name';
} else {
$result['is_valid'] = true;
$result['message'] = '';
}
return $result;
}
Explanation:
^
- anchor at start of string\w+
- 1+ word characters\s
- a single space\w+
- 1+ word characters$
- anchor at end of stringYou might want a more forgiving regex allowing with multiple words:
$pattern = "/^\w+(\s\w+)+$/";
Explanation:
(\s\w+)+
- one or more sequences of space followed by word chars