views:

106

answers:

2

I've noticed in Kohana 3 these error messages provided by default.

return array(
    'not_empty' => ':field must not be empty.',
);

Obviously, :field is replaced with the field name.

Now I am validating an image upload. Obviously, I'm allowing only JPG, JPEG, GIF & PNG.

I have an error message set up like so.

return array(
    'photo' => array(
        'Upload::type' => 'You must upload an image file (JPG, JPEG, GIF, PNG)'
    )
);

I also use Kohana's validation helper like so.

$input->rules('photo', array(
'Upload::type' => array('Upload::type' => array('jpg', 'jpeg', 'png', 'gif'))
));

Is there a way I can use those accepted extensions in my error string, perhaps like...

return array(
    'photo' => array(
        'Upload::type' => 'You can only upload files of :types'
    )
);
+2  A: 

you can access the parameters with :param1 :param2 etc

'error' => 'You can only upload files of :param1, :param2, :param3'

I guess this doesn't work so well with variable amounts of parameters =(

A possible solution would be to use a callback as an alias to the rule, then take the list of allowed formats and send them to the message manually using implode().

ex:

public function valid_type(Validate $array, $field, $formats)
{
    $params = $formats;
    array_unshift($params, $array[$field]);
    if ( ! call_user_func_array(array('Upload', 'type'), $params))
    {
        $array->error($field, 'Upload::type', array('types' => $formats));
    }
}
Zeelot
Should I add a `,` as first argument of `implode()`?
alex
yeah, sorry about that =P it also looks like Kohana does the implode() automatically so you could leave that out (I think) but the rest of the example is good IMO
Zeelot
On second thought, it seems that Upload::type() takes an array of valid types, so the example biakeveron wrote actually works as intended. My example is for rules that take a variable amount of parameters.
Zeelot
+3  A: 

Kohana has this feature "out of the box" :)

So, you should add something like this:

// messages/validate.php
return array(
   'upload::type' => ':field should be one of the following types: [:param1]', 
);
biakaveron
Will that display the first param only though?
alex
Yes. This example means that you use rule as described in question (one param for file types available). Kohana will automatically convert array to string with implode() function.
biakaveron
Remember that your first parameter is an array, so it is treated as a single parameter, not multiple.
shadowhand