Rob Mcg
Rob Mcg

Reputation: 59

Need A Form Field To Validate From A CSV File In Wordpress

I have been hitting a roadblock here, I am a novice coder and a bit rusty as well. The below code works fully in a wordpress functions file but I really want to validate from a CSV file vs entering 2000 lines to validate against.

add_filter('frm_validate_field_entry', 'mobileform_custom_validation', 10, 3);
function mobileform_custom_validation($errors, $posted_field, $posted_value){
if($posted_field->id == 496){ //change 496 to the ID of the field to validate
if(!in_array($posted_value, array('001','002'))){ //change 001 and 002 to your allowed values
  //if it doesn't match up, add an error:
$errors['field'. $posted_field->id] = 'Please contact us.';
}
}
return $errors;
}

Upvotes: 1

Views: 334

Answers (1)

Bar-code
Bar-code

Reputation: 277

This line will get the first column of a csv file into an array:

$list = array_map(function ($line) { return str_getcsv($line)[0]; }, file('../path_to/your_csv_file.csv'));

Then you just have to use it in your test:

if(!in_array($posted_value, $list)){

Your code will then look like:

add_filter('frm_validate_field_entry', 'mobileform_custom_validation', 10, 3);
function mobileform_custom_validation($errors, $posted_field, $posted_value){
    if($posted_field->id == 496){
        $list = array_map(function ($line) { return str_getcsv($line)[0]; }, file('../path_to/your_csv_file.csv'));
        if(!in_array($posted_value, $list)){
            $errors['field'. $posted_field->id] = 'Please contact us.';
        }
    }
    return $errors;
}

But you have to set properly the path to your csv file by replacing

../path_to/your_csv_file.csv

By the real path of your CSV file. I can't do this part for you.

Upvotes: 2

Related Questions