Ever needed to simply validate form data in perl Catalyst framework? Well it turns out to be simpler then you thought. Since Data::FormValidator and Catalyst::Plugin::FormValidator are no longer recommended to be used ( as per Catalyst::Plugin::FormValidator docs ), we will use Catalyst::Plugin::FormValidator::Simple which wraps FormValidator::Simple functionality quite well. If you are needing form construction, rendering and more, you can look at HTML::FormHandler instead.
FormValidator::Simple as the name implies is simple and functional form validation module. It does form validation and nothing more. It has a catalyst plugin which allows us to easily integrate it it into our web application. Here is some code below to illustrate how to use it with custom constraint ( via FormValidator::Simple::Plugin::CustomConstraint ) to validates captcha sequence on the website contact form.
First we load support for captcha, session and formvalidator in MyApp.pm as per below.
use Catalyst qw/
-Debug
Static::Simple
ConfigLoader
Session
Session::Store::FastMmap
Session::State::Cookie
FormValidator::Simple
Captcha
/;
__PACKAGE__->config(
name => 'MyApp',
validator => {
plugins => [ 'CustomConstraint', 'Trim' ]
},
'Plugin::Captcha' => {
session_name => 'captcha_session',
new => {
width => 40,
height => 40,
lines => 1,
gd_font => 'Giant',
thickness => 0,
frame => 0,
rnd_data => [0 .. 9]
},
create => [ 'normal', 'box', '#333333', '#f4f4f4' ],
particle => [ 40 ],
},
'Plugin::Session' => {
expires => 8600
},
);
Next we need to tell our root controller to handle the form processing as per below.
sub process : Local {
#ensure form fields are required ( NOT_BLANK )
#and that they are always whitespace trimmed ( TRIM )
#then use custom constraint via ( CUSTOM_CONSTRAINT )
my $result = $c->form(
name => [ qw/TRIM NOT_BLANK/ ],
email => [ qw/TRIM NOT_BLANK EMAIL_LOOSE/ ],
message => [ qw/TRIM NOT_BLANK/ ],
validate => [
'TRIM',
'NOT_BLANK', [
'CUSTOM_CONSTRAINT',
sub {
my ( $validate, $args ) = @_;
my $result = $c->validate_captcha( $validate );
return $result;
}
]
]
);
if ( $result->has_error ) {
#do something in case of error
} else {
#process the form data as there is no errors
}
}
Lastly we need a template to ensure form rendering. Here is example of one. It will show a single form input, feel free to expand on it to include more inputs as per input specification above.
This shows how to validate form inputs using custom constraints and FormValidator::Simple via catalyst plugin. This example completely separates templating from form validation, so you could always hand off the template to your designer for further layout modifications and so on, without them ever needing to work with perl code.
