Question

I have two colorpicker fields and I am using preg_match to validate them. This is a working code, it validates as expected.
It looks like this (I will give code for first field because second field is basically the same):

function display_bg_setting($args){
//Get our options from register settings (my_theme_color_options);
$GetColorpickerValue = (array) get_option('my_theme_color_options');

if(isset($GetColorpickerValue['display_bg'])) {
$get_options = $GetColorpickerValue['display_bg'];
}   else {
     $GetColorpickerValue['display_bg']='';
     $get_options = $GetColorpickerValue['display_bg'];
    }
echo'<input type="text" id="display_bg" value="'.$get_options.'" name="my_theme_color_options[display_bg]" />';

Now The Question:

Obviously i will have a lot more colorpicker fields in my theme (15-20 fields) so instead validating every single field like in the code above I tried to use a callback function and validate my colors simultaneously. This is where I am failing and my code does not validate colors.

The callback looks like this:

  function validate_color_options_and_other_fields($options){
  //My two colopickers fields stored as an array
  $option = array($options['wrapper_background_color'],$options['display_bg']);

  foreach($option as $options){
    if(preg_grep('/#([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?\b/', $options)) //hex color is valid

    {
         return $options;//Returns colorpicker fields
    } 


     else {//Returns blank
     $options['wrapper_background_color']='';
     $options['display_bg']='';
     } 

    }//End foreach


   return $options;//Returns all other options(checkboxses,select fields...)


}//Function end

This is what I am trying to do:
I put some non-color value on first field and real color on second field so the output would be nothing on first field and real color on second field and vice versa.(This is the part where my callback fails.).
Or I put some non-color values on both fields and it returns nothing on both fields (This is the part where my callback works.)


Can you guys help me out with this?

Was it helpful?

Solution

You are using preg_grep which uses an array as input, but you are giving at a string by your foreach. I think the easiest would be using something like the following code:

$options = array('#fffAA9', '#a65c23');

foreach ($options as $value)
{
    preg_match('/(#[a-f0-9]{3}([a-f0-9]{3})?)/i', $value, $matches);
    if (isset($matches[1]))
    {
        // validated ok
        var_dump($matches[1]);
    }
    else
    {
        // no match
    }
}

edit: Alternativly you can do it with preg_grep even simpler:

public function actionValidate($options)
{
//  $options = array('#fffAA9', '#a65c23');

    return preg_grep('/^(#[a-f0-9]{3}([a-f0-9]{3})?)$/i', $options);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top