Writing custom validation without/before knowing form and field IDs

Hello,

One thing that has been frustrating with Gravity Forms as a developer is not being able to assign custom IDs for forms or fields. This means that more times than not, any code written having to do with Gravity Forms has to have hard coded IDs which makes things more complicated than should be when different environment (testing and prod, for example) don’t have the same content and thus form IDs can’t match.

For example, a client wants us to create a form where we do some email white listing as part of the validation process. This means we have to make sure a form with matching ID and field IDs exists on all dev, testing and prod environments. This type of thing would be MUCH simpler and cleaner if we could simply set custom IDs and say “validate field ‘client_email’ on form ‘info_request’”.

Have I just been doing this wrong for all those years? What’s the suggested method of handling this?

In the past what I’ve done in situations like this is use a custom CSS class on the field and then you check against that in the code since it will be stored in the field object.

For example the following adds custom validation to see if a field has exactly 5 characters entered but only if a field also has the “do_stuff” custom CSS Class added in the field settings:

add_filter( 'gform_field_validation', 'custom_validation', 10, 4 );
function custom_validation( $result, $value, $form, $field ) {

    if ( $result['is_valid'] && strlen( $value ) != 5 && $field->cssClass == 'do_stuff' ) {
        $result['is_valid'] = false;
        $result['message'] = 'Please enter a value with 5 characters.';
    }
    return $result;
}

Karl’s answer is definitely a good one and would require very little re-work of ID based validation.

If the scenarios you are coding for are ones that might apply across different forms / fields / field types, using the gform_field_advanced_settings filter would be worth a look. A checkbox added there would then let you evaluate against field object stored value similar to how Karl’s snippet above checks $field->cssClass does.