[Catalyst] Form validation in insert() and update()?

mla maurice.aubrey at gmail.com
Tue May 15 22:08:45 GMT 2007


Christopher H. Laco wrote:
> Damned if you do... damned if you don't. There is no one correct answer.

So true ;-|

In terms of form validation, what do you guys think of this
interface? It uses perl to handle conditional logic/dependencies
instead of using a spec language like Data::FormValidator.

   # pass a hash ref or object with param() interface to ne
   my $form = MLA::Form->new($params);

   # Validate the data. This terse syntax uses Getopt::Long-style
   # option specifiers.

   $form->check('first_name=s'); # required field first_name
   $form->check('your_email=email'); # required e-mail

   # After doing checks, see if we hit any errors.
   if ($form->error) {
     print "Error: $_\n" foreach $form->error;
   } else { # No errors, validation passed
     # data() returns a hash ref with the validated data
     my $data = $form->data;
   }

Could also check for specific fields failing by

   if ($form->error(qw/ first_name last_name /)) {
     ...
   }

By default, it will convert the field name to a label
name (e.g., first_name => First Name) and use that for the error
messages. So, for example, in the first check, if the first_name
isn't supplied, it would produce an error message like
"First name is required".

You can override that though:

   $form->check('first_name=s', label => "Mother's first name");

Usually you'd subclass the form class to implement the
data types that are specific to your domain.

Other examples of validation checks:

   $form->check('title:s'); # optional title
   # list of colors; if validation passes, $data->{fav_colors} will
   # contain an array ref. Each individual color is checked.
   $form->check('fav_colors:color@')

The verbose interface:

   $form->check(
     field => 'first_name',
     type => 'string',
     max_length => 100,
     label => 'Your first name',
   );

Any unknown arguments are passed into the validation type routine so
you can parameterize your types easily.

Anyone have a problem with this approach? What are the drawbacks?

I originally turned to it because I was hacking Data::FormValidator to
have more complex dependency logic (I think it's added some stuff since
then) and thought you can't beat code for that.

Thanks,

Maurice



More information about the Catalyst mailing list