Have a field validate against an array of account numbers

Here is the PHP I am trying to use to validate a field ONLY if the entry matches one of the account numbers in the array.

Here is my code. It is probably a mess :slight_smile: any help is welcome!

add_filter( 'gform_field_validation_6_166', 'custom_validation', 10, 4 );

function custom_validation( $result, $value, $form, $field ) {
    $valid_numbers = array( '12462916701', '12922121503' );

    if ( $result['is_valid'] && in_array( $value, $valid_numbers ) ) {
        $result['is_valid'] = false;
        $result['message'] = 'Please enter a valid account number';
    }

    return $result;
}

Hi Nathan. Do you want to return the message when the provided account number is NOT in your array? If so, change this line:

if ( $result['is_valid'] && in_array( $value, $valid_numbers ) ) {

to this:

if ( $result['is_valid'] && !in_array( $value, $valid_numbers ) ) {

You may also want to format it like this example (example 3, part 2) from the doc page (separating the first $result['is_valid'] from the actual validation of the account number provided:

add_filter( 'gform_field_validation_2_1', 'custom_zip_validation', 10, 4 );
function custom_zip_validation( $result, $value, $form, $field ) {
    if ( $result['is_valid'] ) {
        $acceptable_zips = array(
            '123',
            '456',
        );
 
        $zip_value = rgar( $value, $field->id . '.5' );
 
        if ( ! in_array( $zip_value, $acceptable_zips ) ) {
            $field->set_input_validation_state( 5, false ); // Only for Gravity Forms 2.5.10 or higher.
            $result['is_valid'] = false;
            $result['message']  = 'Zip validation failed.';
        }
    }
 
    return $result;
}
1 Like

good catch with the !

This is the code I ended up with. It seems to be working as intended.

add_filter( 'gform_field_validation_6_102', 'custom_validation', 10, 4 );
function custom_validation( $result, $value, $form, $field ) { 
	$accountno = array( 
		123, //reference comment
		321, //reference comment
		231, //reference comment
	); 
	if ( $result['is_valid'] && !in_array(intval( $value ), $accountno, $strict = true )) {
		$result['is_valid'] = false;
		$result['message'] = 'Please enter a valid account number';
	}
    return $result;
}

So long as it works, looks good to me!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.