man Embperl::Form::Validate () - Form validation with server- and client-side support.

NAME

Embperl::Form::Validate - Form validation with server- and client-side support.

DESCRIPTION

This modules is developed to do form validation for you. It works on the server side by checking the posted form data and it generates client side script functions, to validate the form values, as far as possible, before they are send to the server, to avoid another server roundtrip.

Also it has the best support for Embperl, it should also work outside of Embperl e.g. with CGI.pm or mod_perl.

It can be extended by new validation rules for additional syntaxes (e.g. US zip codes, German Postleitzahlen, number plates, iso-3166 2-digit language or country codes, etc.)

Each module has the ability to rely it's answer on parameters like e.g. the browser, which caused the request for or submitted the form.

The module fully supports internationalisation. Any message can be provided in multiple languages and it makes use of Embperl's multilanguage support.

SYNOPSIS

 use Embperl::Form::Validate;

 my $epf = new Embperl::Form::Validate($rules, $form_id);

 $epf->add_rule('fnord', $fnord_rules);

 # validate the form values and returns error information, if any
 my $result = $epf -> validate ;

 # Does the form content validate?
 print 'Validate: ' . ($result?'no':'yes');

 # validate the form values and reaturn all error messages, if any
 my $errors = $epf->validate_messages($fdat, $pref);

 # Get the code for a client-side form validation according to the
 # rules given to new:
 $epf -> get_script_code ;

METHODS

The following methods are available: Constructor for a new form validator. Returns a reference to a Embperl::Form::Validate object.

$rules
should be a reference to an array of rules, see RULES elsewhere in this document for details.
$form_id
should be the name (im HTML) or id (in XHTML) parameter of the form tag, which has to be verified.It\'s e.g. used for generating the right path in the JavaScript DOM. It defaults to 'forms[0]' which should be the first form in your page.
$default_language
language to use when no messages are available in the desired language. Defaults to 'en'. Adds rules CW$field_rules for a (new) field CW$field to the validator, e.g.

 $epf->add_rule([ -key => 'fnord', -type => 'Number', -max => 1.3, -name => 'Fnord' ]);

The new rule will be appended to the end of the list of rules.

See RULES elsewhere in this document.

$epf -> validate ([$fdat, [$pref]]);

Does the server-side form validation.

$fdat
should be a hash reference to all postend form values. It defaults to CW%fdat of the current Embperl page.
$pref
can contain addtional information for the validation process. At the moment the keys CWlanguage and CWdefault_language are recognized. CWlanguage defaults to the language set by Embperl. CWdefault_language defaults to the one given with CWnew.

The method verifies the content CW$fdat according to the rules given to the Embperl::Form::Validate constructor and added by the add_rule() method and returns an array refernce to error informations. If there is no error it returns undef. Each element of the returned array contains a hash with the following keys:

key
key into CW$fdat which caused the error
id
message id
typeobj
object reference to the Validate object which was used to validate the field
name
human readable name, if any. Maybe a hash with multiple languages.
msg
field specific messages, if any. Maybe a hash with multiple languages.
param
array with parameters which should subsituted inside the message Converts one item returned by validate into a error message
$err
Item returned by validate
$pref
Preferences (see validate) Validate the form content and returns the error messages as array ref if any. See validate for details.

$epf -> get_script_code ([$pref])

Returns the script code necessary to do the client-side validation. Put the result between <SCRIPT> and </SCRIPT> tags inside your page. It will contain a function that is named CWepform_validate_<name_of_your_form> where <name_of_your_form> is replaced by the form named you have passed to new. You should call this function in the CWonSubmit of your form. Example:

    <script>
    [+ do { local $escmode = 0 ; $epf -> get_script_code } +]
    </script>

    <form name="foo" action="POST" onSubmit="return epform_validate_foo()">
        ....
    </form>

DATA STRUCTURES

The functions and methods expect the named data structures as follows:

RULES

The CW$rules array contains a list of tests to perform. Alls the given tests are process sequenzially. You can group tests together, so when one test fails the remaining tests of the same group are not processed and the processing continues in the next outer group with the next test.

  [
    [
    -key        => 'lang',
    -name       => 'Language'
    required    => 1,
    length_max  => 5,
    ],
    [
    -key        => 'from',
    -type       => 'EMail',
    emptyok     => 1,
    ],

    -key        => ['foo', 'bar']
    required    => 1,
  ]

All items starting with a dash are control elements, while all items without a dash are tests to perform.

-key
gives the key in the passed form data hash which should be tested. -key is normaly the name given in the HTML name attribute within a form field. CW-key can also be a arrayref, in which case only one of the given keys must statisfy the following test to succeed.
-name
is a human readable name that should be used in error messages. Can be hash with multiple languages, e.g.
    -name => { 'en' => 'date', 'de' => 'Datum' }
-type
specfify to not use the standard tests, but the ones for a special type. For example there is a type CWNumber which will replaces all the comparsions by numeric ones instead of string comparisions. You may add your own types by writing a module that contains the necessary test and dropping it under Embperl::Form::Validate::<Typename>. The -type directive also can verfiy that the given data has a valid format for the type. The following types are available:
Default
This one is used when no type is specified. It contains all the standart tests.
Number
Input must be a floating point number.
Integer
Input must be a integer number.
TimeHHMM
Input must be the time in the format hh::mm
TimeHHMMSS
Input must be the time in the format hh::mm:ss
EMail
Input must be a valid email address including a top level domain e.g. user@example.com
EMailRFC
Input must be a valid email adress, no top level domain is required, so user@foo is also valid.
IPAddr
Input must be an ip-address in the form nnn.nnn.nnn.nnn
IPAddr_Mask
Input must be an ip-address and network mask in the form nnn.nnn.nnn.nnn/mm
FQDN_IPAddr
Input must be an ip-address or an fqdn (host.domain) If you write your own type package, make sure to send them back, so they can be part of the next distribution.
-msg
Used to give messages which should be used when the test fails. This message overrides the standart messages provided by Embperl::Form::Validate and by Embperls message management. Can also be a hash with messages for multiple languages. The -msg parameter must preceed the test for which it should be displayed. You can have multiple different messages for different tests, e.g.
       [
        -key        => 'email',
        -name       => 'E-Mail-Address',
        emptyok     => 1,                   # it's ok to leave this field empty (in this case the following tests are skiped)
        -msg => 'The E-Mail-Address is invalid.',
        matches_regex => '(^[^ <>()@¡-ÿ]+@[^ <>()@¡-ÿ]+\.[a-zA-Z]{2,3}$)',
        -msg => 'The E-Mail address must contain a "@".',
        must_contain_one_of => '@',
        -msg => 'The E-Mail address must contain at least one period.',
        must_contain_one_of => '.',
        -msg => 'The E-Mail-Address is invalid. It must only not contain any special charaters.',
        must_not_contain => '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ',
       ],
-fail
stops further validation of any rule after the first error is found
-cont
continues validation in the same group, also a error was found
-break => 1
errors only break current block, but does not display any message. -break => 0 turns bak to normal behaviour. This can be used for preconditions:
    [
    -key => 'action',  emptyok => 1, -break => 1, ne => 0, -break => 0,
    -key => 'input', 'required' => 1
    ]
The above example will only require the field input, when the field action is not empty and is not zero.
[arrayref]
you can place a arrayref with tests at any point in the rules list. The array will be considered as a group and the default is the stop processing of a group as soon as the first error is found and continue with processing with the next rule in the next outer group.

The following test are currently defined:

required
emptyok
length_min
length_max
length_eq
eq
same
Value must be the same as in field given as argument. This is usefull if you want for example verify that two passwords are the same. The Text displayed to the user for the second field maybe added to the argument separeted by a colon. Example:
  $epf = Embperl::Form::Validate -> new (
        [
            -key => 'pass',  -name => 'Password', required => 1, length_min => 4,
            -key => 'pass2', -name => 'Repeat Password', required => 1, length_min => 4,
                             same => 'pass:Password',
        ],
        'passform') ;
ne
lt
gt
le
ge
matches_regex
Value must match Perl regular expression. Only executed on server side.
matches_regex_js
Value must match JavaScript regular expression. Only executed on client side. IMPORTANT: If the user has disabled JavaScript in his browser this test will be never executed. Use a corresponding Perl Regex with CWmatches_regex to get a server side validation. Use this with care, because different browser may have different support for regular expressions.
not_matches_regex
Value must not match Perl regular expression. Only executed on server side.
not_matches_regex_js
Value must not match JavaScript regular expression. Only executed on client side. IMPORTANT: If the user has disabled JavaScript in his browser this test will be never executed. Use a corresponding Perl Regex with CWnot_matches_regex to get a server side validation. Use this with care, because different browser may have different support for regular expressions.
matches_wildcard
must_only_contain
must_not_contain
must_contain_one_of

PREFERENCES

The CW$pref hash (reference) contains information about a single form request or submission, e.g. the browser version, which made the request or submission and the language in which the error messages should be returned. See also validate

ERROR CODES

For a descriptions of the error codes, validate is returning see validate

FDAT

See also Embperl.

 my $fdat = { foo => 'foobar',
              bar => 'baz', 
              baz => 49, 
              fnord => 1.2 };

Example

This example simply validates the form input when you hit submit. If your input is correct, the form is redisplay with your input, otherwise the error message is shown. If you turn off JavaScript the validation is still done one the server-side. Any validation for which no JavaScript validation is defined (like regex matches), only the server-side validation is performed.

    <html>
    <head>
    [-

    use Embperl::Form::Validate ;

    $epf = Embperl::Form::Validate -> new (
        [
            [
            -key => 'name',
            -name => 'Name',
            required => 1,
            length_min => 4,
            ],
            [
            -key => 'id',
            -name => 'Id',
            -type => 'Number',
            gt   => 0,
            lt   => 10,
            ],
            [
            -key => 'email',
            -msg => 'This is not a valid E-Mail address',
            must_contain_one_of => '@.',
            matches_regex => '..+@..+\\...+',
            length_min => 8,
            ],
            [
            -key => 'msg',
            -name => 'Message',
            emptyok => 1,
            length_min => 10,
            ]
        ]) ;

    if ($fdat{check})
        {
        $errors = $epf -> validate_messages ;
        }

    -]
    <script>
    [+ do { local $escmode = 0 ; $epf -> get_script_code } +]
    </script>
    </head>
    <body>

    <h1>Embperl Example - Input Form Validation</h1>

    [$if @$errors $]
        <h3>Please correct the following errors</h3>
        [$foreach $e (@$errors)$]
            <font color="red">[+ $e +]</font><br>
        [$endforeach$]
    [$else$]
        <h3>Please enter your data</h3>
    [$endif$]

    <form action="formvalidation.htm" method="GET" onSubmit="return epform_validate_forms_0_()">
      <table>
        <tr><td><b>Name</b></td> <td><input type="text" name="name"></td></tr>
        <tr><td><b>Id (1-9)</b></td> <td><input type="text" name="id"></td></tr>
        <tr><td><b>E-Mail</b></td> <td><input type="text" name="email"></td></tr>
        <tr><td><b>Message</b></td> <td><input type="text" name="msg"></td></tr>
        <tr><td colspan=2><input type="submit" name="check" value="send"></td></tr>
      </table>
    </form>

    <p><hr>

    <small>Embperl (c) 1997-2005 G.Richter / ecos gmbh <a href="http://www.ecos.de">www.ecos.de</a></small>

    </body>
    </html>

See also eg/x/formvalidation.htm

SEE ALSO

See also Embperl.

AUTHOR

Axel Beckert (abe@ecos.de) Gerald Richter (richter@dev.ecos.de)