Validation::Class::Plugins - Basic Instructions for Writing Plugins
This documentation serves as a brief overview on writing plugins for Validation::Class. Here are the key points:
Validation::Class is written with Moose and a plugin must be designed as a Moose::Role. As a role the plugins attributes and methods are imported into the calling class and because of this it is important to name your attributes and methods cautiously as to not overwrite another plugins functionality.
When creating official Validation::Class plugins you should use the namespace Validation::Class::Plugin::YourPluginName. This will allow users of your plugin to simply pass YourPluginName to the load_plugins() method. Otherwise you will need to pass the fully-qualified plugin package name prefixed with a "+" symbol. The following is an example of including a plugin.
package MyApp::Validation; use Validation::Class; load_plugins __PACKAGE__, 'YourPluginName', '+MyApp::Validation::YourPluginName'; # a validation rule field 'login' => { label => 'User Login', error => 'Login invalid.', required => 1, validation => sub { my ($self, $this_field, $all_params) = @_; return $this_field->{value} eq 'admin' ? 1 : 0; } }; # a validation rule field 'password' => { label => 'User Password', error => 'Password invalid.', required => 1, validation => sub { my ($self, $this_field, $all_params) = @_; return $this_field->{value} eq 'pass' ? 1 : 0; } }; 1;
Your plugin is loaded at runtime and can manipulate the Validation::Class object by declaring a new method. The following is an example of a ficticious plugin for formatting telephone numbers:
package Validation::Class::Plugin::TelephoneFormatting; use Moose::Role; # hook into the instantiation process # of the calling class at runtime sub new { my ($class, $self) = @_; # US Telephones $self->filters->{telephone_usa} = sub { my $phone = shift; $phone =~ s/\D//g; my ($area, $prefix, $xchng) = $phone =~ m/1?(\d{3})(\d{3})(\d{4}); return "+1 ($area) $prefix-$xchng"; }; }
Once we create, test and deploy our plugin, we can use it in our code as follows:
package MyApp::Validation; use Validation::Class; __PACKAGE__->load_plugins('TelephoneFormatting'); # a validation rule field 'phone' => { label => 'Telephone Number', error => 'Phone number invalid.', required => 1, filters => 'telephone_usa', pattern => '+1 (###) ###-####' }; package main ; my $rules = MyApp::Validation; # ...
Al Newkirk <awncorp@cpan.org>
This software is copyright (c) 2011 by awncorp.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
To install Validation::Class, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Validation::Class
CPAN shell
perl -MCPAN -e shell install Validation::Class
For more information on module installation, please visit the detailed CPAN module installation guide.