Form::Validate(3pm)

πŸ“¦
version 2.5.0 Β· 2 versions
, in ubuntu jammy

πŸ’– Form::Validate(3pm) πŸ’–

okay so bestie, welcome to the Form::Validate(3pm) page β€” the manual name you're looking for is Embperl::Form::Validate, and it is literally here to do form validation with server- and client-side support. Periodt. 🫢✨

✨ NAME ✨

  • Embperl::Form::Validate β€” Form validation with server- and client-side support. πŸ’…

🌸 DESCRIPTION 🌸

This module 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. No extra roundtrip? We love to see it. 😌

It has the best support for Embperl, and it should also work outside of Embperl e.g. with CGI.pm or mod_perl. Versatile icon behavior. πŸ¦‹

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. (Yes, it can read the room β€” I mean, the browser.) πŸ‘‘

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:

πŸ’– $epf = Embperl::Form::Validate -> new ($rules [, $form_id ], [$default_language], [$charset]);

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'. 🌍
  • $charset β€” Pass 'utf-8' in case you want utf-8 messages. πŸ’œ

πŸ¦‹ $epf->add_rules($field, $field_rules);

Adds rules $field_rules for a (new) field $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 %fdat of the current Embperl page. πŸ“
  • $pref β€” can contain additional information for the validation process. At the moment the keys "language" and "default_language" are recognized. "language" defaults to the language set by Embperl. "default_language" defaults to the one given with "new". πŸ—£οΈ

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

  • key β€” key into $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

πŸ’… $epf -> error_message ($err, [ $pref ])

Converts one item returned by validate into a error message. 😭

  • $err β€” Item returned by validate
  • $pref β€” Preferences (see validate)

🌸 $epf -> validate_messages ($fdat, [ $pref ])

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 "epform_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 "onSubmit" 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 πŸ’–

okay so all the functions and methods out here are expecting their named data structures to look a very specific way, bestie. here's the tea on each one:


πŸŽ€ RULES πŸŽ€

the $rules array is literally just a list of tests to run. every single test you hand over gets processed sequentially, one after the other, no cutting the line. you can also group tests together β€” and the way that works is: when one test in a group fails, the remaining tests of that same group are not processed at all πŸ’€, and processing just continues on in the next outer group with the next test. slay.

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

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

here's the whole vibe check: every item starting with a dash is a control element (the settings, the knobs, the levers), and everything without a dash is a test to perform. no cap.

✨ the control elements ✨

  • -key β€” this gives you the key in the passed form data hash that's about to get tested. -key is normally the name you wrote in the HTML name attribute inside a form field. and plot twist: -key can also be an arrayref 🫢, and in that case only one of the given keys has to satisfy the following test for it to succeed.
  • -name β€” a human readable name, used in error messages. can be a hash with multiple languages, like:
    -name => { 'en' => 'date', 'de' => 'Datum' }
  • -type β€” tells the thing to not use the standard tests, but the ones for a special type instead. for example there's a type "Number" which swaps all the comparisons out for numeric ones instead of string comparisons. you can absolutely add your own types by writing a module that contains the necessary test and dropping it under Embperl::Form::Validate::<Typename>. the -type directive can also verify that the given data has a valid format for the type. πŸ‘‘

here are the types that are available, bestie:

  • Default β€” the one used when no type is specified. it contains all the standard tests.
  • Number β€” input must be a floating point number.
  • Integer β€” input must be a integer number.
  • PosInteger β€” input must be a integer number and greater or equal zero.
  • TimeHHMM β€” input must be the time in the format hh::mm
  • TimeHHMMSS β€” input must be the time in the format hh::mm:ss
  • TimeValue β€” input must be a number followed by s, m, h, d or w.
  • 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 address, 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)
  • select β€” this one gets used together with required and causes Embperl::Form::Validate to test whether a selected index != 0 instead of a non empty input.
and if you write your own type package? send them back, bestie πŸ₯Ί so they can be part of the next distribution. contributing is main character energy fr fr.
  • -msg β€” used to give messages that should be used when the test fails. this message overrides the standard messages provided by Embperl::Form::Validate and by Embperl's message management. can also be a hash with messages for multiple languages. the -msg parameter must precede the test for which it should be displayed. you can have multiple different messages for different tests, like:
       [
        -key        => 'email',
        -name       => 'E-Mail-Address',
        emptyok     => 1,                   # it's ok to leave this field empty (in this case the following tests are skipped)

        -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 => '.',
       ],
  • -fail β€” stops further validation of any rule after the first error is found.
  • -cont β€” continues validation in the same group, even though a error was found.
  • -break => 1 β€” errors only break the current block, but do not display any message. -break => 0 turns back 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 to stop processing a group as soon as the first error is found and continue processing with the next rule in the next outer group.

πŸ¦‹ the tests, currently defined πŸ¦‹

the following tests are currently defined. some of them come with deets in the original, some are just out here living their truth with a name and nothing else β€” but no gatekeeping, every single one is listed:

  • required
  • emptyok
  • length_min
  • length_max
  • length_eq
  • eq
  • same β€” value must be the same as in the field given as argument. super useful if you wanna verify that two passwords are the same, for example. the text displayed to the user for the second field may be added to the argument separated 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 never be executed. use a corresponding Perl Regex with "matches_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 never be executed. use a corresponding Perl Regex with "not_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
  • checked β€” checkbox must be selected
  • notchecked β€” checkbox must not be selected

πŸ’œ PREFERENCES πŸ’œ

the $pref hash (reference) contains information about a single form request or submission β€” like, 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 that validate is returning, see validate. iykyk.


🌈 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 redisplayed with your input; otherwise the error message is shown. and if you turn off JavaScript? the validation is still done on the server-side. for any validation that has no JavaScript validation defined (like regex matches), only the server-side validation is performed. periodt.

    <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-2010 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 at embperl dot org)


okay bestie that's literally the whole page, you ate that πŸ’… this was perl v5.34.0, dated 2022-02-06, and the page itself is Form::Validate(3pm) β€” go forth and validate, you've got this πŸ¦‹πŸ’–πŸŒΈ

πŸ“¦ where this page comes from