Timothy's Dev Stuff

A collection of code snippets and other developer things.

Gravity Forms Validation Filtering

The code below was used in an instance where conditional validation was needed. It was requested to have validation for phone or email to be required, but not to require both. To do this, the gform_validation filter was used. The filter calls a custom function that checks the phone and email fields and, if they are both empty, validation fails. With this, we achieve the intended result. If a phone number is entered but no email, they are not both empty so validation passes. The same goes if an email is entered and no phone.
// Gravity Form Validation for Phone OR Email address
add_filter( 'gform_validation_1', 'validate_phone_or_email', 10, 2 );
function validate_phone_or_email( $validation_result ) {
    $form = $validation_result['form'];

    if ( empty( rgpost( 'input_2' ) ) && empty( rgpost( 'input_3' ) ) ) {
        $validation_result['is_valid'] = false;
        foreach ( $form['fields'] as &$field ) {
            if ( $field->type == 'phone' || $field->type == 'email' ) {
                $field->failed_validation = true;
                $field->validation_message = 'You must enter a valid phone number <strong>or</strong> email address.';
            }
        }
    }

	return $validation_result;
}

You  can read more on the documentation for this filter here: https://docs.gravityforms.com/gform_validation/