Making 1 of 2 fields required?

I am doing some basic checks using gform_field_validation. The below checks the correct format for 2 different fields in the same form (field 12 and 13).

By default, both fields are optional. However, I want to get a little more complex now, and make at least one of the fields required. That is, if field 12 is empty field 13 is required, OR if field 13 is empty field 12 is required.

What changes would I need to make for the more complex logic?

/**
 * Validate 11 numbers for ABN
 */
add_filter( 'gform_field_validation_1_12', 'validate_abn', 10, 4 );
    function validate_abn( $result, $value, $form, $field ) {

    $pattern = "/^[0-9]{11,}$/";

        if ( !empty( $value ) && !preg_match( $pattern, $value ) ) {
            $result['is_valid'] = false;
            $result['message']  = 'Invalid ABN format';
        }    	   

    return $result;
}

/**
 * Validate 9 numbers for ACN
 */
add_filter( 'gform_field_validation_1_13', 'validate_acn', 10, 4 );
    function validate_acn( $result, $value, $form, $field ) {

    $pattern = "/^[0-9]{9,}$/";

        if ( !empty( $value ) && !preg_match( $pattern, $value ) ) {
            $result['is_valid'] = false;
            $result['message']  = 'Invalid ACN format';
        }    	   

    return $result;
}

Hi Andy. Can you offer a radio button choice which says something like “Which format will you provide?” and the choices are “ABN” and “ACN”. Then, you can make both field 12 and 13 required, and show one or the other conditionally based on the radio button choice. Will that work for you?

1 Like

Thx for the response Chris. Yes, that approach would work for the web form. However, I’m sending data via API, so ideally the checks for such a rule would be done during submission POST.

Appreciate any further thoughts to add the more complex logic?

Hi Andy. Depending on your code, you should be able to check for the value in the $_POST, or by using the gform_validation or gform_field_validation filter:

If you share you code here we may be able to help further.