I need to validate incoming data in several controllers of a web app before storing in a DB (DBIx::Class
). Basically, I need to validate the value for each column using a callback (anonymous sub). I initially thought about using Params::Validate
in each controller. But this approach has two problems:
There's no easy way to handle validation errors with
Params::Validate
, as it simply dies on the first invalid param with an error string.
I have to duplicate the validation logic for every column in all the controllers, which violates the DRY principle.
I think the best way would be to make the validation logic part of the model. What's the prefered way to do this in DBIx::Class
?
To add validation callbacks to the columns metadata use add_columns
in the Result class, e.g.
__PACKAGE__->add_columns(
'+mycolumn' => {
validate => sub {
my ($schema, $val) = @_;
# validate $val, possibly using $schema
},
},
...
);
To facilitate the use of these callbacks, you can create a DBIx::Class сomponent.