Eugene Yarmash
Eugene Yarmash

Reputation: 150061

What's the preferred way to validate data for a row in DBIx::Class?

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:

  1. 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.

  2. 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?

Upvotes: 4

Views: 677

Answers (2)

Eugene Yarmash
Eugene Yarmash

Reputation: 150061

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.

Upvotes: 0

Ωmega
Ωmega

Reputation: 43683

I am not sure what and how exactly you want to validate your data, but did you try to use DBIx::Class::Validation for your needs? It should fit.

Upvotes: 1

Related Questions