Name field, first name, set minimum characters [RESOLVED]

Please can you let me know where I’m going wrong? Would like this to apply to the first name of all name fields, to stop people just putting an initial, which we cannot have in insurance. Thanks.

add_filter( 'gform_field_validation', function ( $result, $value, $form, $field ) {
    
if ( 'name' === $field->type && $field->isRequired ) {

        GFCommon::log_debug( __METHOD__ . '(): Running.' );

        // Input values.
        

        $first  = rgar( $value, $field->id . '.3' );

        
         
        $name_field = array( '3' => $first);
'min_chars' => 3,
'max_chars' => 15,
'min_validation_message' => 3 ( 'Please enter full first name.' ),
'max_validation_message' => 15 ( 'Too long.' )

 
            }
    GFCommon::log_debug( __METHOD__ . '(): Returning validation result.' );

    return $result;

}, 10, 4 );

Try the following:

add_filter( 'gform_field_validation', function ( $result, $value, $form, $field ) {
    if ( 'name' === $field->type && $field->isRequired ) {
        GFCommon::log_debug( current_filter() . '(): Running.' );
        $first = rgar( $value, $field->id . '.3' );
        if ( $result['is_valid'] && strlen( $first ) > 15 ) {
            $result['is_valid'] = false;
            $result['message'] = 'Please enter only full first name.';
            GFCommon::log_debug( current_filter() . '(): Returning too long validation result.' );
            return $result;
        }
        if ( $result['is_valid'] && strlen( $first ) < 3 ) {
            $result['is_valid'] = false;
            $result['message'] = 'Please enter full first name.';
            GFCommon::log_debug( current_filter() . '(): Returning too short validation result.' );
            return $result;
        }
        GFCommon::log_debug( current_filter() . '(): Returning unchanged validation result.' );
    }
    return $result;
}, 10, 4 );

The line rgar( $value, $field->id . ‘.3’ ); is getting the value that was input the the first name field – which always has an input ID of 3 in Name fields.

1 Like

Thanks Joshua, that works. Appreciate time from both of you.

Regards
Steve

2 Likes