.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.43) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Validation::Class::Cookbook 3pm" .TH Validation::Class::Cookbook 3pm "2023-06-11" "perl v5.36.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Validation::Class::Cookbook \- Recipes for Validation::Class .SH "VERSION" .IX Header "VERSION" version 7.900059 .SH "GUIDED TOUR" .IX Header "GUIDED TOUR" The instructions contained in this documentation are also relevant for configuring any class derived from Validation::Class. The validation logic that follows is not specific to a particular use-case. .SS "Parameter Handling" .IX Subsection "Parameter Handling" There are three ways to declare parameters you wish to have validated. The first and most common approach is to supply the target parameters to the validation class constructor: .PP .Vb 1 \& use Validation::Class::Simple; \& \& my $rules = Validation::Class::Simple\->new(params => $params); .Ve .PP All input parameters are wrapped by the Validation::Class::Params container which provides generic functionality for managing hashes. Additionally you can declare parameters by using the params object directly: .PP .Vb 1 \& use Validation::Class::Simple; \& \& my $rules = Validation::Class::Simple\->new; \& \& $rules\->params\->clear; \& \& $rules\->params\->add(user => \*(Aqadmin\*(Aq, pass => \*(Aqs3cret\*(Aq); \& \& printf "%s parameters were submitted", $rules\->params\->count; .Ve .PP Finally, any parameter which has corresponding validation rules that has been declared in a validation class derived from Validation::Class will have an accessor which can be used directly or as an argument to the constructor: .PP .Vb 1 \& package MyApp::Person; \& \& use Validation::Class; \& \& field \*(Aqname\*(Aq => { \& required => 1 \& }; \& \& package main; \& \& my $rules = MyApp::Person\->new(name => \*(AqEgon Spangler\*(Aq); \& \& $rules\->name(\*(AqEgon Spengler\*(Aq); .Ve .SS "Validation Rules" .IX Subsection "Validation Rules" Validation::Class comes with a complete standard set of validation rules which allows you to easily describe the constraints and operations that need to be performed per parameter. .PP Validation rules are referred to as \fIfields\fR, fields are named after the parameters they expect to be matched against. A field is also a hashref whose keys are called directives which correspond with the names of classes in the directives namespace, and whose values are arguments which control how directives carry-out their operations. .PP .Vb 1 \& use Validation::Class::Simple; \& \& my $rules = Validation::Class::Simple\->new; \& \& $rules\->fields\->clear; \& \& $rules\->fields\->add(name => { required => 1, max_length => 255 }); .Ve .PP Fields can be specified as an argument to the class constructor, or managed directly using the Validation::Class::Fields container. Every field is wrapped by the Validation::Class::Field container which provides accessors for all core directives. Directives can be found under the directives namespace, e.g. the required directive refers to Validation::Class::Directive::Required. Please see Validation::Class::Directives for a list of all core directives. .SS "Flow Control" .IX Subsection "Flow Control" A good data validation tool is not simply checking input against constraints, its also providing a means to easily handle different and often complex data input scenarios. .PP The queue method allows you to designate and defer fields to be validated. It also allows you to set fields that must be validated regardless of what has been passed to the validate method. Additionally it allows you to conditionally specify constraints: .PP .Vb 1 \& use Validation::Class::Simple; \& \& my $rules = Validation::Class::Simple\->new; \& \& $rules\->queue(\*(Aqname\*(Aq); # always validate the name parameter \& \& $rules\->queue(\*(Aqemail\*(Aq, \*(Aqemail2\*(Aq) if $rules\->param(\*(Aqchange_email\*(Aq); \& $rules\->queue(\*(Aqlogin\*(Aq, \*(Aqlogin2\*(Aq) if $rules\->param(\*(Aqchange_login\*(Aq); \& \& # validate name \& # validate email and email confirmation if change_email is true \& # validate login and login confirmation if change_login is true \& \& $rules\->validate(\*(Aqpassword\*(Aq); # additionally, validate password \& $rules\->clear_queue; # reset the queue when finished .Ve .PP Akin to the queue method is the stash method. At-times it is necessary to break out of the box in order to design constraints that fit your particular use-case. The stash method allows you to share arbitrary objects with routines used by validation classes. .PP .Vb 1 \& use Validation::Class::Simple; \& \& my $rules = Validation::Class::Simple\->new; \& \& $rules\->fields\->add( \& email => { \& # email validation relies on a stashed object \& validation => sub { \& my ($self, $field, $params) = @_; \& return 0 if ! my $dbo = $self\->stash(\*(Aqdbo\*(Aq); \& return 0 if ! $dbo\->email_exists($field\->value); \& return 1; \& } \& } \& ); \& \& # elsewhere in the program \& $rules\->stash(dbo => $database_object); # stash the database object .Ve .SS "Error Handling" .IX Subsection "Error Handling" When validation fails, and it will, you need to be able to report what failed and why. Validation::Class give you complete control over error handling and messages. Errors can exist at the field-level and class-level (errors not specific to a particular field). All errors are wrapped in a Validation::Class::Errors container. .PP .Vb 1 \& use Validation::Class::Simple; \& \& my $rules = Validation::Class::Simple\->new; \& \& # print a comma separated list of class and field errors \& print $rules\->errors_to_string unless $rules\->validate; \& \& # print a newline separated list of class and field errors \& print $rules\->errors_to_string("\en") unless $rules\->validate; \& \& # print a comma separated list of class and upper\-cased field errors \& print $rules\->errors_to_string(undef, sub{ ucfirst lc shift }) \& \& # print total number of errors at the class and field levels \& print "Found %s errors", $rules\->error_count; \& \& # return a hashref of fields with errors \& my $errors = $rules\->error_fields; \& \& # get errors for specific fields only \& my @errors = $rules\->get_errors(\*(Aqemail\*(Aq, \*(Aqlogin\*(Aq); .Ve .SS "Input Filtering" .IX Subsection "Input Filtering" Filtering data is one fringe benefits of a good data validation framework. The process is also known as scrubbing or sanitizing data. The process ensures that the data being passed to the business logic will be clean and consistent. .PP Filtering data is not as simple and straight-forward as it may seem which is why it is necessary to think-through your applications interactions before implementation. .PP Filtering is the process of applying transformations to the incoming data. The problem with filtering is that it permanently alters the data input and in the event of a failure could report inconsistent error messages: .PP .Vb 1 \& use Validation::Class::Simple; \& \& my $rules = Validation::Class::Simple\->new; \& \& $rules\->fields\->add( \& # even if the input is submitted as lowercase it will fail \& # the filter is run as a pre\-process by default \& username => { \& filters => [\*(Aquppercase\*(Aq], \& validation => sub { \& return 0 if $_[1]\->value =~ /[A\-Z]/; \& return 1; \& } \& } \& ); .Ve .PP When designing a system to filter data, it is always necessary to differentiate pre-processing filters from post-processing filters. Validation::Class provides a filtering directive which designates certain fields to run filters in post-processing: .PP .Vb 11 \& $rules\->fields\->add( \& # if the input is submitted as lowercase it will pass \& username => { \& filters => [\*(Aquppercase\*(Aq], \& filtering => \*(Aqpost\*(Aq, \& validation => sub { \& return 0 if $_[1]\->value =~ /[A\-Z]/; \& return 1; \& } \& } \& ); .Ve .SS "Handling Failures" .IX Subsection "Handling Failures" A data validation framework exists to handle failures, it is its main function and purpose, in-fact, the difference between a validation framework and a type-constraint system is how it responds to errors. .PP When a type-constraint system finds an error it raises an exception. Exception handling is the process of responding to the occurrence, during computation, of exceptions (anomalous or exceptional situations). .PP Typically the errors reported when an exception is raised includes a dump of the program's state up until the point of the exception which is apropos as exceptions are unexpected. .PP A data validation framework can also be thought-of as a type system but one that is specifically designed to expect input errors and report user-friendly error messages. .PP Validation::Class may encounter exceptions as programmers defined validation rules which remain mutable. Validation::Class provides attributes for determining how the validation engine reacts to exceptions and validation failures: .PP .Vb 1 \& use Validation::Class::Simple; \& \& my $rules = Validation::Class::Simple\->new( \& ignore_failure => 1, # do not throw errors if validation fails \& ignore_unknown => 0, # throw errors if unknown directives are found \& report_failure => 0, # register errors if "method validations" fail \& report_unknown => 0, # register errors if "unknown directives" are found \& ); .Ve .SS "Data Validation" .IX Subsection "Data Validation" Once your fields are defined and you have your parameter rules configured as desired you will like use the validate method to perform all required operations. The validation operations occur in the following order: .PP .Vb 4 \& normalization (resetting fields, clearing existing errors, etc) \& pre\-processing (applying filters, etc) \& validation (processing directives, etc) \& post\-processing (applying filters, etc) .Ve .PP What gets validated is determined by the state and arguments passed to the validate method. The validate method determines what to validate in the following order: .PP .Vb 4 \& checks the validation queue for fields \& checks arguments for regular expression objects and adds matching fields \& validates fields with matching parameters if no fields are specified \& validates all fields if no parameters are specified .Ve .PP It is also important to under what it means to declare a field as being required. A field is a data validation rule matching a specific parameter, A required field simply means that if-and-when a parameter is submitted, it is required to have a value. It does not mean that a field is always required to be validated. .PP Occasionally you may need to temporarily set a field as required or not-required for a specific validation operation. This requirement is referred to as the toggle function. The toggle function is enacted by prefixing a field name with a plus or minus sign (+|\-) when passed to the validate method: .PP .Vb 1 \& use Validation::Class::Simple; \& \& my $rules = Validation::Class::Simple\->new(fields => {...}); \& \& # meaning, email is always required to have a value \& # however password and password2 can be submitted as empty strings \& # but if password and password2 have values they will be validated \& $rules\->validate(\*(Aq+email\*(Aq, \*(Aq\-password\*(Aq, \*(Aq\-password2\*(Aq); .Ve .PP Here are a few examples and explanations of using the validate method: .PP .Vb 1 \& use Validation::Class::Simple; \& \& my $rules = Validation::Class::Simple\->new(fields => {...}); \& \& unless ($rules\->validate) { \& # validate all fields with matching parameters \& } \& \& unless ($rules\->validate) { \& # validate all fields because no parameters were submitted \& } \& \& unless ($rules\->validate(qr/^email/)) { \& # validate all fields whose name being with email \& # e.g. email, email2, email_update \& } \& \& unless ($rules\->validate(\*(Aqlogin\*(Aq, \*(Aqpassword\*(Aq)) { \& # validate the login and password specifically \& # regardless of what parameters have been set \& } \& \& unless ($rules\->validate({ user => \*(Aqlogin\*(Aq, pass => \*(Aqpassword\*(Aq })) { \& # map user and pass parameters to the appropriate fields as aliases \& # and validate login and password fields using the aliases \& } .Ve .SH "BUILDING CLASSES" .IX Header "BUILDING CLASSES" This recipe displays the usage of keywords to configure a validation class. .SS "Problem" .IX Subsection "Problem" You want to know how to use the Validation::Class keywords to define a validation class. .SS "Solution" .IX Subsection "Solution" Use the keywords exported by Validation::Class to register validation rules, templates, profiles, methods and filters. .SS "Discussion" .IX Subsection "Discussion" Your validation class can be thought of as your data\-model/input\-firewall. The benefits this approach provides might require you to change your perspective on parameter handling and workflow. Typically when designing an application we tend to name parameters arbitrarily and validate the same data at various stages during a program's execution in various places in the application stack. This approach is inefficient and prone to bugs and security problems. .PP To get the most out of Validation::Class you should consider each parameter hitting your application (individually) as a transmission fitting a very specific criteria, yes, like a field in a data model. .PP Your validation rules will act as filters which will reject or accept and format the transmission for use within your application, yes, almost exactly like a firewall. .PP A validation class is defined as follows: .PP .Vb 1 \& package MyApp::Person; \& \& use Validation::Class; \& \& # a validation rule template \& \& mixin \*(Aqbasic\*(Aq => { \& required => 1, \& min_length => 1, \& max_length => 255, \& filters => [\*(Aqlowercase\*(Aq, \*(Aqalphanumeric\*(Aq] \& }; \& \& # a validation rule \& \& field \*(Aqlogin\*(Aq => { \& mixin => \*(Aqbasic\*(Aq, \& label => \*(Aquser login\*(Aq, \& error => \*(Aqlogin invalid\*(Aq, \& validation => sub { \& \& my ($self, $field, $params) = @_; \& \& return $field\->value eq \*(Aqadmin\*(Aq ? 1 : 0; \& \& } \& }; \& \& # a validation rule \& \& field \*(Aqpassword\*(Aq => { \& mixin => \*(Aqbasic\*(Aq, \& label => \*(Aquser password\*(Aq, \& error => \*(Aqpassword invalid\*(Aq, \& validation => sub { \& \& my ($self, $field, $params) = @_; \& \& return $field\->value eq \*(Aqpass\*(Aq ? 1 : 0; \& \& } \& }; \& \& # a validation profile \& \& profile \*(Aqregistration\*(Aq => sub { \& \& my ($self, @args) = @_; \& \& return $self\->validate(qw(login password)); \& \& }; \& \& # an auto\-validating method \& \& method \*(Aqregisters\*(Aq => { \& \& input => \*(Aqregistration\*(Aq, \& using => sub { \& \& my ($self, @args) = shift; \& \& # ... do something \& \& } \& \& }; \& \& 1; .Ve .PP The fields defined will be used to validate the specified input parameters. You specify the input parameters at/after instantiation, parameters should take the form of a hashref of key/value pairs passed to the params attribute, or attribute/value pairs. The following is an example on using your validate class to validate input in various scenarios: .PP .Vb 2 \& # web app \& package MyApp; \& \& use MyApp::User; \& use Misc::WebAppFramework; \& \& get \*(Aq/auth\*(Aq => sub { \& \& # get user input parameters \& my $params = shift; \& \& # initialize validation class and set input parameters \& my $user = MyApp::User\->new(params => $params); \& \& unless ($user\->registers) { \& \& # print errors to browser unless validation is successful \& return $user\->errors_to_string; \& \& } \& \& return \*(Aqyou have authenticated\*(Aq; \& \& }; .Ve .PP A field can have aliases, parameter names that if detected will be mapped to the parameter name matching the field definition. Multiple fields cannot have the same alias defined, such a configuration would result in a runtime error. .PP .Vb 1 \& use MyApp::User; \& \& my $user = MyApp::User\->new(params => $params); \& \& unless ($user\->validate) { \& \& return $input\->errors_to_string; \& \& } \& \& package MyApp::User; \& \& field \*(Aqemail\*(Aq => { \& ..., \& alias => [ \& \*(Aqemails\*(Aq, \& \*(Aqemail_address\*(Aq, \& \*(Aqemail_addresses\*(Aq \& ] \& \& }; \& \& package main; \& \& use MyApp::User; \& \& my $user = MyApp::User\->new(params => { email_address => \*(Aq...\*(Aq }); \& \& unless ($user\->validate(\*(Aqemail\*(Aq){ \& \& return $user\->errors_to_string; \& \& } \& \& # valid because email_address is an alias on the email field .Ve .SH "INTEGRATING CLASSES AND FRAMEWORKS" .IX Header "INTEGRATING CLASSES AND FRAMEWORKS" This recipe displays methods of configuring your validation class to cooperate with your pre-existing classes and object-system. .SS "Problem" .IX Subsection "Problem" You want to know how to configure Validation::Class to cooperate with pre-existing classes or object systems like Mo, Moo, Mouse, and Moose. .SS "Solution" .IX Subsection "Solution" Use a combination of techniques such as excluding keywords exported by Validation::Class and utilizing the initialize_validator method. .SS "Discussion" .IX Subsection "Discussion" Validation::Class will atuomatically inject a method name `initialize_validator` if a pre-existing `new` method is dicovered which allows you to execute certain validation class normalization routines. When, the initialize_validator method is called is not important, it is only important that it is called before your object is used as a validation class object. .PP A validation class using Moose as an object system could be configured as follows: .PP .Vb 1 \& package MyApp::Person; \& \& use Moose; \& use Validation::Class qw(fld mxn); \& \& # the order in which these frameworks are used is important \& # loading Moose first ensures that the Moose::Object constructor \& # has precedence \& \& sub BUILD { \& \& my ($self, $params) = @_; \& \& $self\->initialize_validator($params); \& \& } \& \& mxn \*(Aqbasic\*(Aq => { \& required => 1, \& min_length => 1, \& max_length => 255, \& filters => [\*(Aqlowercase\*(Aq, \*(Aqalphanumeric\*(Aq] \& }; \& \& fld \*(Aqlogin\*(Aq => { \& mixin => \*(Aqbasic\*(Aq, \& label => \*(Aquser login\*(Aq, \& error => \*(Aqlogin invalid\*(Aq \& }; \& \& fld \*(Aqpassword\*(Aq => { \& mixin => \*(Aqbasic\*(Aq, \& label => \*(Aquser password\*(Aq, \& error => \*(Aqpassword invalid\*(Aq \& }; \& \& has \*(Aqprofile\*(Aq => ( \& is => \*(Aqrw\*(Aq, \& isa => \*(AqMyApp::Person::Profile\*(Aq \& ); \& \& 1; .Ve .SH "FILTERING DATA" .IX Header "FILTERING DATA" This recipe describes how to define filtering in your validation class rules. .SS "Problem" .IX Subsection "Problem" You want to know how to define filters to sanatize and transform your data although some transformations may need to occur after a successful validation. .SS "Solution" .IX Subsection "Solution" Data validation rules can be configured to apply filtering as both pre-and-post processing operations. .SS "Discussion" .IX Subsection "Discussion" Validation::Class supports pre/post filtering but is configured to pre-filter incoming data by default. This means that based upon the filtering options supplied within the individual fields, filtering will happen before validation (technically at instantiation and again just before validation). As expected, this is configurable via the filtering attribute. .PP A \s-1WORD OF CAUTION:\s0 Validation::Class is configured to pre-filter incoming data which boosts application security and is best used with passive filtering (e.g. converting character case \- filtering which only alters the input in predictable ways), versus aggressive filtering (e.g. formatting a telephone number) which completely and permanently changes the incoming data ... so much so that if the validation still fails ... errors that are reported may not match the data that was submitted. .PP If you're sure you'd rather employ aggressive filtering, I suggest setting the filtering attribute to 'post' for post-filtering or setting it to null and applying the filters manually by calling the \fBapply_filters()\fR method. .SH "DELEGATING VALIDATION" .IX Header "DELEGATING VALIDATION" This recipe describes how to separate validation logic between multiple related classes. .SS "Problem" .IX Subsection "Problem" You want to know how to define multiple validation classes and pass input data and input parameters between them. .SS "Solution" .IX Subsection "Solution" Use classes as validation domains, as a space to logically group related validation rules, then use built-in methods to have multiple validation classes validate in-concert. .SS "Discussion" .IX Subsection "Discussion" For larger applications where a single validation class might become cluttered and inefficient, Validation::Class comes equipped to help you separate your validation rules into separate classes. .PP The idea is that you'll end up with a main validation class (most likely empty) that will simply serve as your point of entry into your relative (child) classes. The following is an example of this: .PP .Vb 1 \& package MyApp::User; \& \& use Validation::Class; \& \& field name => { ... }; \& field email => { ... }; \& field login => { ... }; \& field password => { ... }; \& \& package MyApp::Profile; \& \& use Validation::Class; \& \& field age => { ... }; \& field sex => { ... }; \& field birthday => { ... }; \& \& package MyApp; \& \& use Validation::Class; \& \& set classes => 1; \& \& package main; \& \& my $input = MyApp\->new(params => $params); \& \& my $user = $input\->class(\*(Aquser\*(Aq); \& \& my $profile = $input\->class(\*(Aqprofile\*(Aq); \& \& 1; .Ve .SH "INTROSPECT AND EXTEND" .IX Header "INTROSPECT AND EXTEND" This recipe describes how to peek under the curtain and leverage the framework for other purposes. .SS "Problem" .IX Subsection "Problem" You want to know how to use your data validation classes to perform other tasks programmatically (e.g. generate documentation, etc). .SS "Solution" .IX Subsection "Solution" By using the prototype class associated with your validation class you can introspect it's configuration and perform additional tasks programmatically. .SS "Discussion" .IX Subsection "Discussion" Most users will never venture beyond the public \s-1API,\s0 but powerful abilities await the more adventureous developer and this section was written specifically for you. To assist you on along your journey, let me explain exactly what happens when you define and instantiate a validation class. .PP Classes are defined using keywords (field, mixin, filter, etc) which register rule definitions on a cached class profile (of-sorts) associated with the class which is being constructed. On instantiation, the cached class profile is cloned then merged with any arguments provided to the constructor, this means that even in a persistent environment the original class profile is never altered. .PP To begin introspection, simply look into the attributes attached to the class prototype, e.g. fields, mixins, filters, etc., the following examples will give you an idea of how to use introspection to extend your application code using Validation::Class. .PP Please keep in mind that Validation::Class is likely to already have most of the functionalty you would need to introspect your codebase. The following is an introspection design template that will work in most cases: .PP .Vb 1 \& package MyApp::Introspect; \& \& use Validation::Class; \& \& load classes => \*(AqMyApp\*(Aq; # load MyApp and all child classes \& \& sub per_class { \& \& my ($self, $code) = @_; \& \& my %relatives = %{$self\->proto\->settings\->{relatives}}; \& \& while (my($parent, $children) = each(%relatives)) { \& \& while (my($nickname, $namespace) = each(%{$children})) { \& \& # do something with each class \& $code\->($namespace); \& \& } \& \& } \& \& } \& \& sub per_field_per_class { \& \& my ($self, $code) = @_; \& \& $self\->per_class(sub{ \& \& my $namespace = shift; \& \& my $class = $namespace\->new; \& \& foreach my $field ($class\->fields\->values) { \& \& # do something with each field in each class \& $code\->($class, $class\->fields\->{$field}); \& \& } \& \& }); \& \& } .Ve .SH "CLIENT-SIDE VALIDATION" .IX Header "CLIENT-SIDE VALIDATION" This recipe describes how to generate \s-1JSON\s0 objects which can be used to validate user input in the web-browser (client-side). .SS "Problem" .IX Subsection "Problem" You want to know how to make the most out of your data validation rules by making your configuration available as \s-1JSON\s0 objects in the browser. .SS "Solution" .IX Subsection "Solution" Using introspection, you can leverage the prototype class associated with your validation class to generate \s-1JSON\s0 objects based on your validation class configuration. .SS "Discussion" .IX Subsection "Discussion" In the context of a web-application, it is often best to perform the initial input validation on the client (web-browser) before submitting data to the server for further validation and processing. In the following code we will generate javascript objects that match our Validation::Class data models which we will then use with some js library to validate form data, etc. .PP \&... example validation class .PP .Vb 1 \& package MyApp::Model; \& \& use Validation::Class; \& use Validation::Class::Plugin::JavascriptObjects; \& \& mxn scrub => { \& filters => [\*(Aqtrim\*(Aq, \*(Aqstrip\*(Aq] \& }; \& \& fld login => { \& mixin => \*(Aqscrub\*(Aq \& email => 1, \& required => 1, \& alias => \*(Aquser\*(Aq, \& }; \& \& fld password => { \& mixin => \*(Aqscrub\*(Aq, \& required => 1, \& alias => \*(Aqpass\*(Aq, \& min_length => 5, \& min_symbols => 1, \& min_alpha => 1, \& min_digits => 1 \& }; .Ve .PP \&... in your webapp controller .PP .Vb 1 \& get \*(Aq/js/model\*(Aq => sub { \& \& my $model = MyApp::Model\->new; \& \& # generate the JS object \& my $data = $model\->plugin(\*(Aqjavascript_objects\*(Aq)\->render( \& namespace => \*(Aqvalidate.model\*(Aq, \& fields => [qw/email password/], \& include => [qw/required email minlength maxlength/] \& ) \& \& return print $data; \& \& }; .Ve .PP The output of the /js/model route should generate a javascript object which looks similar to the following: .PP .Vb 10 \& var validate = { \& "model" : { \& "email" : { \& "minlength" : 3, \& "required" : 1, \& "maxlength" : 255 \& }, \& "password" : { \& "minlength" : 5, \& "required" : 1, \& "maxlength" : 255 \& } \& } \& }; .Ve .PP If its not obvious yet, we can now easily use this generated javascript \s-1API\s0 with jQuery (or other client-side library) to validate form data, etc. .PP .Vb 10 \& \& \& \& AUTH REQUIRED \& \& \& \& \& \& \&
[% input.errors_to_string %]
\&
\&
\&

Halt, who goes there?

\&
\&
\&
\&
\&
\&
\&
\& \& .Ve .SH "AUTHOR" .IX Header "AUTHOR" Al Newkirk .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" This software is copyright (c) 2011 by Al Newkirk. .PP This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.