blib/lib/Embperl/Form/Validate.pm untested

filter: Statementstmt 0.0% 0 / 247 Branchbran 0.0% 0 / 148 Conditioncond 0.0% 0 / 119 MC/DCmcdc 0.0% 0 / 61 Subroutinesub 0.0% 0 / 15 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 603 CC 75 SCAR 62.5
CC
75
Cov
0%
gather_script_code
870.0
validate_rules
650.0
build_message
272.0
CRAP 516.3
1  
2 ###################################################################################
3 #
4 # Embperl - Copyright (c) 1997-2008 Gerald Richter / ecos gmbh www.ecos.de
5 # Embperl - Copyright (c) 2008-2015 Gerald Richter
6 # Embperl - Copyright (c) 2015-2023 actevy.io
7 #
8 # You may distribute under the terms of either the GNU General Public
9 # License or the Artistic License, as specified in the Perl README file.
10 #
11 # THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
12 # IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
13 # WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
14 #
15 ###################################################################################
16  
17  
18 package Embperl::Form::Validate;
19  
20 use strict;
21 use vars qw($VERSION $has_encode);
22  
23 BEGIN
24 {
25 eval "require Encode" ;
26 $has_encode = $@?0:1 ;
27 }
28  
29  
30 $VERSION = '3.0.1' ;
31  
32 =encoding iso8859-1
33  
34 =head1 NAME
35  
36 Embperl::Form::Validate - Form validation with server- and client-side support.
37  
38 =head1 DESCRIPTION
39  
40 This modules is developed to do form validation for you. It works
41 on the server side by checking the posted form data and it
42 generates client side script functions, to validate the
43 form values, as far as possible, before they are send to
44 the server, to avoid another server roundtrip.
45  
46 Also it has the best support for Embperl, it should also work
47 outside of Embperl e.g. with CGI.pm or mod_perl.
48  
49 It can be extended by new validation rules for
50 additional syntaxes (e.g. US zip codes, German
51 Postleitzahlen, number plates, iso-3166 2-digit language or country
52 codes, etc.)
53  
54 Each module has the ability to rely it's answer on parameters like
55 e.g. the browser, which caused the request for or submitted the form.
56  
57 The module fully supports internationalisation. Any message can be
58 provided in multiple languages and it makes use of Embperl's
59 multilanguage support.
60  
61 =head1 SYNOPSIS
62  
63 use Embperl::Form::Validate;
64  
65 my $epf = new Embperl::Form::Validate($rules, $form_id);
66  
67 $epf->add_rule('fnord', $fnord_rules);
68  
69 # validate the form values and returns error information, if any
70 my $result = $epf -> validate ;
71  
72 # Does the form content validate?
73 print 'Validate: ' . ($result?'no':'yes');
74
75 # validate the form values and reaturn all error messages, if any
76 my $errors = $epf->validate_messages($fdat, $pref);
77  
78 # Get the code for a client-side form validation according to the
79 # rules given to new:
80 $epf -> get_script_code ;
81  
82 =head1 METHODS
83  
84 The following methods are available:
85  
86 =head2 $epf = Embperl::Form::Validate -> new ($rules [, $form_id ], [$default_language], [$charset]);
87  
88 Constructor for a new form validator. Returns a reference to a
89 Embperl::Form::Validate object.
90  
91 =over
92  
93 =item $rules
94  
95 should be a reference to an array of rules, see L<"RULES"> elsewhere in this
96 document for details.
97  
98 =item $form_id
99  
100 should be the name (im HTML) or id (in XHTML) parameter of
101 the form tag, which has to be verified.It\'s e.g. used for
102 generating the right path in the JavaScript DOM. It defaults to 'forms[0]'
103 which should be the first form in your page.
104  
105 =item $default_language
106  
107 language to use when no messages are available in the desired language.
108 Defaults to 'en'.
109  
110 =item $charset
111  
112 Pass 'utf-8' in case you want utf-8 messages.
113  
114 =back
115  
116 =cut
117  
118 sub new
119 {
120 my $invokedby = shift;
121 my $class = ref($invokedby) || $invokedby;
122 my ($frules, $form_id, $default_language, $charset) = @_ ;
123  
124 my $self = {
125 form_id => $form_id || 'forms[0]', # The name
126 frules => $frules || [], # \@frules
127 default_language => $default_language || 'en',
128 charset => $charset || 'iso8859-15',
129 };
130 bless($self, $class);
131 $self->init;
132 return $self;
133 }
134  
135 ###
136 ### init() yet undocumented. The only purpose of init() is too allow
137 ### to add functionality without rewriting the whole new() method.
138 ###
139  
140 sub init # $self
141 {
142 my $self = shift;
143 return 1;
144 }
145  
146 =head2 $epf->add_rules($field, $field_rules);
147  
148 Adds rules $field_rules for a (new) field $field to the validator,
149 e.g.
150  
151 $epf->add_rule([ -key => 'fnord', -type => 'Number', -max => 1.3, -name => 'Fnord' ]);
152  
153 The new rule will be appended to the end of the list of rules.
154  
155 See L<"RULES"> elsewhere in this document.
156  
157 =cut
158  
159 sub add_rule # $self, $field, \%rules
160 {
161 my $self = shift;
162 my $rules = shift;
163  
164 push @{$self->{frules}}, $rules;
165 return 1;
166 }
167  
168  
169  
170  
171 =head2 $epf -> validate ([$fdat, [$pref]]);
172  
173 Does the server-side form validation.
174  
175 =over
176  
177 =item $fdat
178  
179 should be a hash reference to all postend form values.
180 It defaults to %fdat of the current Embperl page.
181  
182 =item $pref
183  
184 can contain additional information for the validation process.
185 At the moment the keys C<language> and C<default_language>
186 are recognized. C<language> defaults to the language set by
187 Embperl. C<default_language> defaults to the one given with C<new>.
188  
189 =back
190  
191 The method verifies the content $fdat according to the rules given
192 to the Embperl::Form::Validate
193 constructor and added by the add_rule() method and returns an
194 array reference to error information. If there is no error it
195 returns undef. Each element of the returned array contains a hash with
196 the following keys:
197  
198 =over
199  
200 =item key
201  
202 key into $fdat which caused the error
203  
204 =item id
205  
206 message id
207  
208 =item typeobj
209  
210 object reference to the Validate object which was used to validate the field
211  
212 =item name
213  
214 human readable name, if any. Maybe a hash with multiple languages.
215  
216 =item msg
217  
218 field specific messages, if any. Maybe a hash with multiple languages.
219  
220 =item param
221  
222 array with parameters which should subsituted inside the message
223  
224 =back
225  
226 =cut
227  
228  
229 sub loadtype
230 {
231 my ($self, $type) = @_ ;
232  
233
234 eval "require $type;";
235 die 'Died inside '.__PACKAGE__.'::loadtype::eval: '.$@ if $@;
236 return $type;
237 }
238  
239  
240 sub newtype
241 {
242 my ($self, $type) = @_ ;
243  
244 $type ||= 'Default';
245 $type = 'Embperl::Form::Validate::'.$type
246 unless $type =~ m!(::|/)!;
247  
248 my $obj = $self -> {typeobjs}{$type} ;
249 return $obj if ($obj) ;
250
251 $type = $self -> loadtype ($type) ;
252  
253 $obj = $self -> {typeobjs}{$type} = $type -> new ;
254  
255 return $obj ;
256 }
257  
258  
259  
260 sub validate_rules
261 {
262 my ($self, $frules, $fdat, $pref, $result, $key, $name) = @_ ;
263  
264 my %param ;
265 my $type ;
266 my $typeobj ;
267 my $i ;
268 my $keys = [] ;
269 my $status ;
270 my $msg ;
271 my $break = 0 ;
272 my @key_stack ;
273
274 while ($i < @$frules)
275 {
276 my $action = $frules -> [$i++] ;
277 if (ref $action eq 'ARRAY')
278 {
279 my $fail = $self -> validate_rules ($action, $fdat, $pref, $result, $key, $name) ;
280 return $fail if ($fail) ;
281 }
282 elsif (ref $action eq 'CODE')
283 {
284 my $arg = $frules -> [$i++] ;
285 foreach my $k (@$keys)
286 {
287 $status = &$action($k, $fdat -> {$k}, $arg, $fdat, $pref) ;
288 last if (!$status) ;
289 }
290 }
291 elsif ($action =~ /^-(.*?)$/)
292 {
293 if ($1 eq 'key')
294 {
295 $key = $frules->[$i++] ;
296 $keys = ref $key?$key:[$key] ;
297 $type = 'Default' ;
298 $typeobj = $self -> newtype ($type) ;
299 $name = undef ;
300 $msg = undef ;
301 }
302 elsif ($1 eq 'key_check')
303 {
304 push @key_stack, $key ;
305 $key = $frules->[$i++] ;
306 $keys = ref $key?$key:[$key] ;
307 $type = 'Default' ;
308 $typeobj = $self -> newtype ($type) ;
309 $break = 1 ;
310 }
311 elsif ($1 eq 'key_end')
312 {
313 $key = pop @key_stack ;
314 $keys = ref $key?$key:[$key] ;
315 $break = 0 ;
316 }
317 elsif ($1 eq 'frontend_only')
318 {
319 last ;
320 }
321 elsif ($1 eq 'backend_only')
322 {
323 ;
324 }
325 elsif ($1 eq 'name')
326 {
327 $name = $i++ ;
328 }
329 elsif ($1 eq 'msg')
330 {
331 $msg = $i++ ;
332 }
333 elsif ($1 eq 'break')
334 {
335 $break = $frules->[$i++] ;
336 }
337 elsif ($1 eq 'type')
338 {
339 $type = $frules->[$i++] ;
340 $typeobj = $self -> newtype ($type) ;
341 foreach my $k (@$keys)
342 {
343 $status = $typeobj -> validate ($k, $fdat -> {$k}, $fdat, $pref) ;
344 last if (!$status) ;
345 }
346 }
347 else
348 {
349 $param{$1} = 1 ;
350 }
351 }
352 else
353 {
354 my $arg = $frules -> [$i++] ;
355 foreach my $k (@$keys)
356 {
357 my $method = 'validate_' . $action ;
358 $status = $typeobj -> $method ($k, $fdat -> {$k}, $arg, $fdat, $pref) ;
359 last if (!$status) ;
360 }
361 }
362
363 if ($status)
364 {
365 if (@$status && !$break)
366 {
367 my $id = $status -> [0] ;
368 push @$result, { typeobj => $typeobj, id => $id, key => $key, ($name?(name => $frules -> [$name]):()), ($msg?(msg => $frules -> [$msg]):()), param => $status} ;
369 }
370 last if (!$param{cont})
371 }
372 }
373 return $param{fail} ;
374 }
375  
376  
377  
378  
379 sub validate
380 {
381 my ($self, $fdat, $pref, $epreq) = @_ ;
382  
383 $epreq ||= $Embperl::req ;
384 $fdat ||= $epreq -> thread -> form_hash ;
385  
386 my @result ;
387 $self -> validate_rules ($self->{frules}, $fdat, $pref, \@result) ;
388  
389 return \@result ;
390 }
391  
392  
393 sub build_message
394 {
395 my ($self, $id, $key, $name, $msg, $param, $typeobj, $pref, $epreq, $escape) = @_ ;
396  
397 my $language = $pref -> {language} ;
398 my $default_language = $pref -> {default_language} || $self -> {default_language} ;
399 my $charset = $pref -> {charset} ;
400 my $txt ;
401 if ($name eq '')
402 {
403 if (!ref $key)
404 {
405 $name = $epreq?$epreq -> gettext('attr:' . $key):$key ;
406 }
407 else
408 {
409 my @name ;
410 foreach my $k (@$key)
411 {
412 push @name, $epreq?$epreq -> gettext('attr:' . $k):$k ;
413 }
414 $name = join (($language =~ /^de/)?' oder ':' or ', @name) ;
415 }
416 }
417 if (ref $name eq 'ARRAY')
418 {
419 my @names ;
420 foreach my $n (@$name)
421 {
422 push @names, ref $n ? ($n -> {"$language.$charset"} || $n -> {"$default_language.$charset"} || $n -> {$language} || $n -> {$default_language} || (each %$n)[1] || $key):$n ;
423 }
424 $name = join (', ', @names) ;
425 }
426 else
427 {
428 $name = ref $name ? ($name -> {"$language.$charset"} || $name -> {"$default_language.$charset"} || $name -> {$language} || $name -> {$default_language} || (each %$name)[1] || $key):$name ;
429 }
430  
431 if ($msg)
432 {
433 $txt = ref $msg ? ($msg -> {"$language.$charset"} || $msg -> {"$default_language.$charset"} || $msg -> {$language} || $msg -> {$default_language} || (each %$msg)[1] || undef):$msg ;
434 $txt = $epreq -> gettext ($msg) if ($epreq && ($msg =~ /^\w\w\w:/)) ;
435 }
436 else
437 {
438 $txt = $typeobj -> getmsg ($id, "$language.$charset", "$default_language.$charset") ;
439 $txt ||= $typeobj -> getmsg ($id, $language, $default_language) ;
440 }
441 $txt = $epreq -> gettext($id) if (!$txt && $epreq) ;
442 $txt ||= "Missing Message $id: %0 %1 %2 %3" ;
443 $id = $param -> [0] ;
444 $param -> [0] = $name ;
445 $param -> [0] =~ s/(?<!\\)\'/\\'/g if ($escape) ;
446 my @param ;
447 eval "require Encode" ;
448 if ($charset && $has_encode)
449 {
450 @param = map { Encode::encode($charset, $_) } @$param ;
451 }
452 else
453 {
454 @param = @$param ;
455 }
456
457 $txt =~ s/(?<!\\)\'/\\'/g if ($escape) ;
458 $txt =~ s/%(\d+)/$param[$1]/g ;
459 $param -> [0] = $id ;
460  
461 return $txt ;
462 }
463  
464  
465 =pod
466  
467 =head2 $epf -> error_message ($err, [ $pref ])
468  
469 Converts one item returned by validate into a error message
470  
471 =over
472  
473 =item $err
474  
475 Item returned by validate
476  
477 =item $pref
478  
479 Preferences (see L<validate>)
480  
481 =back
482  
483 =cut
484  
485  
486 sub error_message
487 {
488 my ($self, $err, $pref, $epreq) = @_ ;
489  
490 $epreq ||= $Embperl::req ;
491  
492 return $self -> build_message ($err -> {id}, $err -> {key}, $err -> {name}, $err -> {msg}, $err -> {param}, $err -> {typeobj}, $pref, $epreq) ;
493 }
494  
495  
496 =pod
497  
498 =head2 $epf -> validate_messages ($fdat, [ $pref ])
499  
500 Validate the form content and returns the error messages
501 as array ref if any. See L<validate> for details.
502  
503 =cut
504  
505  
506 sub validate_messages
507 {
508 my ($self, $fdat, $pref, $epreq) = @_ ;
509
510 $epreq ||= $Embperl::req ;
511 $pref -> {language} ||= $epreq -> param -> language if ($epreq) ;
512 $pref -> {default_language} ||= $self -> {default_language} ;
513 $pref -> {charset} ||= $self -> {charset} ;
514  
515 my $result = $self -> validate ($fdat, $pref, $epreq) ;
516 return [] if (!@$result) ;
517  
518 my @msgs ;
519 foreach my $err (@$result)
520 {
521 my $msg = $self -> build_message ($err -> {id}, $err -> {key}, $err -> {name}, $err -> {msg}, $err -> {param}, $err -> {typeobj}, $pref, $epreq) ;
522 push @msgs, $msg ;
523 }
524  
525 return \@msgs ;
526 }
527  
528  
529  
530 sub gather_script_code
531 {
532 my ($self, $frules, $pref, $epreq, $key, $name) = @_ ;
533  
534 my %param ;
535 my $type ;
536 my $typeobj ;
537 my $i ;
538 my $keys = [] ;
539 my $status ;
540 my $msg ;
541 my $msgparam ;
542 my $language = $pref -> {language} ;
543 my $default_language = $pref -> {default_language} || 'en' ;
544 my $scriptcode = $self -> {scriptcode} ||= {} ;
545 my $script = '' ;
546 my $form = $self -> {form_id} ;
547 my $break = 0 ;
548 my @key_stack ;
549  
550 while ($i < @$frules)
551 {
552 my $arg ;
553 my $method ;
554 my $action = $frules -> [$i++] ;
555 if (ref $action eq 'ARRAY')
556 {
557 $script .= $self -> gather_script_code ($action, $pref, $epreq, $key, $name) ;
558 }
559 elsif (ref $action eq 'CODE')
560 {
561 $i++ ;
562 }
563 elsif ($action =~ /^-(.*?)$/)
564 {
565 if ($1 eq 'key')
566 {
567 $key = $frules->[$i++] ;
568 $keys = ref $key?$key:[$key] ;
569 $type = 'Default' ;
570 $typeobj = $self -> newtype ($type) ;
571 $name = undef ;
572 $msg = undef ;
573 }
574 elsif ($1 eq 'key_check')
575 {
576 push @key_stack, $key ;
577 $key = $frules->[$i++] ;
578 $keys = ref $key?$key:[$key] ;
579 $type = 'Default' ;
580 $typeobj = $self -> newtype ($type) ;
581 $break = 1 ;
582 }
583 elsif ($1 eq 'key_end')
584 {
585 $key = pop @key_stack ;
586 $break = 0 ;
587 }
588 elsif ($1 eq 'frontend_only')
589 {
590 ;
591 }
592 elsif ($1 eq 'backend_only')
593 {
594 last ;
595 }
596 elsif ($1 eq 'name')
597 {
598 $name = $i++ ;
599 }
600 elsif ($1 eq 'msg')
601 {
602 $msg = $i++ ;
603 }
604 elsif ($1 eq 'break')
605 {
606 $break = $frules->[$i++] ;
607 }
608 elsif ($1 eq 'type')
609 {
610 $type = $frules->[$i++] ;
611 $typeobj = $self -> newtype ($type) ;
612 $method = 'getscript_validate' ;
613 $arg = '' ;
614 }
615 else
616 {
617 $param{$1} = 1 ;
618 }
619 }
620 else
621 {
622 $method = 'getscript_' . $action ;
623 $arg = $frules -> [$i++] ;
624 }
625
626 if ($method)
627 {
628 my $code ;
629 my $ret ;
630 my $k = "$type*$action*$arg" ;
631 if (!exists ($scriptcode -> {$k}))
632 {
633 if ($typeobj -> can ($method))
634 {
635 ($code, $msgparam) = $typeobj -> $method ($arg, $pref, $form) ;
636 $scriptcode -> {$k} = [$code, $msgparam] ;
637 }
638 else
639 {
640 $code = '' ;
641 $scriptcode -> {$k} = '' ;
642 }
643 }
644 else
645 {
646 if ($scriptcode -> {$k})
647 {
648 $code = $scriptcode -> {$k}[0] ;
649 $msgparam = $scriptcode -> {$k}[1] ;
650 }
651 }
652  
653 if ($code)
654 {
655 my $nametxt = $name?$frules -> [$name]:undef ;
656 my $msgtxt = $msg?$frules -> [$msg]:undef ;
657 my $setmsg = '' ;
658 if ($msgparam && !$break)
659 {
660 my $txt = $self -> build_message ($msgparam -> [0], $key, $nametxt, $msgtxt, $msgparam, $typeobj, $pref, $epreq, 1) ;
661 $setmsg = "ids[i] = '$key' ; msgs[i++]='$txt';"
662 }
663 if (!ref $key)
664 {
665 $script .= "obj = formelem\['$key'\] ; if (obj && !($code)) { $setmsg " . ($param{fail}?'fail=1;break;':($param{cont}?'':'break;')) . "}\n" ;
666 }
667 else
668 {
669 foreach my $k (@$keys)
670 {
671 $script .= "obj = formelem\['$k'\] ; if (obj && !($code)) {" ;
672 }
673
674 $script .= " $setmsg " . ($param{fail}?'fail=1;break;':($param{cont}?'':'break;')) . "\n" ;
675 foreach my $k (@$keys)
676 {
677 $script .= "}" ;
678 }
679 }
680 }
681 }
682 }
683 if ($script)
684 {
685 return qq{
686 do {
687 $script
688 } while (0) ; if (fail) break ;
689 } ;
690 }
691 return '' ;
692 }
693  
694  
695 =pod
696  
697 =head2 $epf -> get_script_code ([$pref])
698  
699 Returns the script code necessary to do the client-side validation.
700 Put the result between <SCRIPT> and </SCRIPT> tags inside your page.
701 It will contain a function that is named C<epform_validate_<name_of_your_form>>
702 where <name_of_your_form> is replaced by the form named you have passed
703 to L<new>. You should call this function in the C<onSubmit> of your form.
704 Example:
705  
706 <script>
707 [+ do { local $escmode = 0 ; $epf -> get_script_code } +]
708 </script>
709  
710 <form name="foo" action="POST" onSubmit="return epform_validate_foo()">
711 ....
712 </form>
713  
714 =cut
715  
716  
717 sub get_script_code
718 {
719 my ($self, $pref, $epreq) = @_ ;
720  
721 $epreq ||= $Embperl::req ;
722 $pref ||= {} ;
723 $pref -> {language} ||= $epreq -> param -> language if ($epreq) ;
724 $pref -> {default_language} ||= $self -> {default_language} ;
725 $pref -> {charset} ||= $self -> {charset} ;
726
727 my $script ;
728 $script = $self -> gather_script_code ($self->{frules}, $pref, $epreq) ;
729 my $fname = $self -> {form_id} ;
730
731 $fname =~ s/([^a-zA-Z0-9_])/_/g ;
732  
733 return qq{
734  
735 function epform_validate_$fname(return_msgs, failed_class, formelem)
736 {
737 var msgs = new Array ;
738 var ids = new Array ;
739 var fail = 0 ;
740 var i = 0 ;
741 var obj ;
742  
743 if (!formelem)
744 formelem = document.$fname ;
745
746 do {
747 $script ;
748 }
749 while (0) ;
750 if (failed_class)
751 {
752 var key ;
753 var i ;
754 for (key in ids)
755 {
756 var elems = formelem\[ids[key]\] ;
757 if (elems)
758 {
759 if (!(elems instanceof NodeList))
760 elems = [elems] ;
761 if (elems[0] instanceof NodeList)
762 elems = elems[0] ;
763 for (i = 0; i < elems.length ;i++)
764 {
765 var elem = elems[i] ;
766 if (elem.getAttribute('type') == 'radio')
767 elem = elem.parentElement ;
768 var eclass = elem.getAttribute('class') ;
769 elem.setAttribute ('class', eclass + ' ' + failed_class) ;
770 elem.setAttribute ('title', msgs[key]) ;
771 }
772 }
773 }
774 }
775
776 if (return_msgs)
777 {
778 var ret = [msgs, ids] ;
779 return ret ;
780 }
781
782 if (i)
783 alert (msgs.join('\\n')) ;
784  
785 return !i ;
786 }
787 } ;
788 }
789  
790  
791  
792 =head1 DATA STRUCTURES
793  
794 The functions and methods expect the named data structures as follows:
795  
796 =head2 RULES
797  
798 The $rules array contains a list of tests to perform. Alls the given tests
799 are process sequenzially. You can group tests together, so when one test fails
800 the remaining tests of the same group are not processed and the processing
801 continues in the next outer group with the next test.
802  
803 [
804 [
805 -key => 'lang',
806 -name => 'Language'
807 required => 1,
808 length_max => 5,
809 ],
810 [
811 -key => 'from',
812 -type => 'EMail',
813 emptyok => 1,
814 ],
815  
816 -key => ['foo', 'bar']
817 required => 1,
818 ]
819  
820  
821 All items starting with a dash are control elements, while all items
822 without a dash are tests to perform.
823  
824 =over
825  
826 =item -key
827  
828 gives the key in the passed form data hash which should be tested. -key
829 is normally the name given in the HTML name attribute within a form field.
830 C<-key> can also be a arrayref, in which case B<only one of> the given keys
831 must satisfy the following test to succeed.
832  
833 =item -key_break
834  
835 same as -key and -break => 1 without reseting name -name and -msg.
836  
837 =item -name
838  
839 is a human readable name that should be used in error messages. Can be
840 hash with multiple languages, e.g.
841  
842 -name => { 'en' => 'date', 'de' => 'Datum' }
843  
844 =item -type
845  
846 specfify to not use the standard tests, but the ones for a special type.
847 For example there is a type C<Number> which will replace all the comparisons
848 by numeric ones instead of string comparisons. You may add your own types
849 by writing a module that contains the necessary test and dropping it under
850 Embperl::Form::Validate::<Typename>. The -type directive also can verify
851 that the given data has a valid format for the type.
852  
853 The following types are available:
854  
855 =over
856  
857 =item Default
858  
859 This one is used when no type is specified. It contains all the standard
860 tests.
861  
862 =item Number
863  
864 Input must be a floating point number.
865  
866 =item Integer
867  
868 Input must be a integer number.
869  
870 =item PosInteger
871  
872 Input must be a integer number and greater or equal zero.
873  
874 =item TimeHHMM
875  
876 Input must be the time in the format hh::mm
877  
878 =item TimeHHMMSS
879  
880 Input must be the time in the format hh::mm:ss
881  
882 =item TimeValue
883  
884 Input must be a number followed by s, m, h, d or w.
885  
886 =item EMail
887  
888 Input must be a valid email address including a top level domain
889 e.g. user@example.com
890  
891 =item EMailRFC
892  
893 Input must be a valid email address, no top level domain is required,
894 so user@foo is also valid.
895  
896 =item IPAddr
897  
898 Input must be an ip-address in the form nnn.nnn.nnn.nnn
899  
900 =item IPAddr_Mask
901  
902 Input must be an ip-address and network mask in the form nnn.nnn.nnn.nnn/mm
903  
904 =item FQDN_IPAddr
905  
906 Input must be an ip-address or an fqdn (host.domain)
907  
908 =item select
909  
910 This used together with required and causes Embperl::Form::Validate
911 to test of a selected index != 0 instead of a non empty input.
912  
913 =back
914  
915  
916 If you write your own type package,
917 make sure to send them back, so they can be part of the next distribution.
918  
919 =item -msg
920  
921 Used to give messages which should be used when the test fails. This message
922 overrides the standard messages provided by Embperl::Form::Validate and
923 by Embperl's message management. Can also be a hash with messages for multiple
924 languages. The -msg parameter must precede the test for which it should be
925 displayed. You can have multiple different messages for different tests, e.g.
926  
927 [
928 -key => 'email',
929 -name => 'E-Mail-Address',
930 emptyok => 1, # it's ok to leave this field empty (in this case the following tests are skipped)
931
932 -msg => 'The E-Mail-Address is invalid.',
933 matches_regex => '(^[^ <>()@¡-ÿ]+@[^ <>()@¡-ÿ]+\.[a-zA-Z]{2,3}$)',
934
935 -msg => 'The E-Mail address must contain a "@".',
936 must_contain_one_of => '@',
937
938 -msg => 'The E-Mail address must contain at least one period.',
939 must_contain_one_of => '.',
940 ],
941  
942  
943 =item -fail
944  
945 stops further validation of any rule after the first error is found
946  
947 =item -cont
948  
949 continues validation in the same group, also a error was found
950  
951 =item -break => 1
952  
953 errors only break current block, but does not display any message.
954 -break => 0 turns bak to normal behaviour. This can be used for preconditions:
955  
956 [
957 -key => 'action', emptyok => 1, -break => 1, ne => 0, -break => 0,
958 -key => 'input', 'required' => 1
959 ]
960  
961 The above example will only require the field "input", when the field "action" is
962 not empty and is not zero.
963  
964 =item -key_check, -key_end
965  
966 Is used for preconditions, same example as for -break
967  
968 [
969 -key => 'input',
970 -key_check => 'action', emptyok => 1, ne => 0, -key_end,
971 'required' => 1
972 ]
973  
974 The above example will only require the field "input", when the field "action" is
975 not empty and is not zero.
976  
977 =item backend_only
978  
979 The following rules will only executed in the backend
980  
981 =item frontend_only
982  
983 The following rules will only executed in the fronend
984  
985 =item [arrayref]
986  
987 you can place a arrayref with tests at any point in the rules list. The array will
988 be considered as a group and the default is the stop processing of a group as soon
989 as the first error is found and continue with processing with the next rule in the
990 next outer group.
991  
992 =back
993  
994 The following test are currently defined:
995  
996 =over
997  
998 =item required
999  
1000 =item emptyok
1001  
1002 =item length_min
1003  
1004 =item length_max
1005  
1006 =item length_eq
1007  
1008 =item eq
1009  
1010 =item same
1011  
1012 Value must be the same as in field given as argument. This is useful
1013 if you want for example verify that two passwords are the same. The
1014 Text displayed to the user for the second field may be added to the argument
1015 separated by a colon. Example:
1016  
1017 $epf = Embperl::Form::Validate -> new (
1018 [
1019 -key => 'pass', -name => 'Password', required => 1, length_min => 4,
1020 -key => 'pass2', -name => 'Repeat Password', required => 1, length_min => 4,
1021 same => 'pass:Password',
1022 ],
1023 'passform') ;
1024  
1025  
1026 =item ne
1027  
1028 =item lt
1029  
1030 =item gt
1031  
1032 =item le
1033  
1034 =item ge
1035  
1036 =item matches_regex
1037  
1038 Value must match B<Perl> regular expression. Only executed on server side.
1039  
1040 =item matches_regex_js
1041  
1042 Value must match B<JavaScript> regular expression. Only executed on client side.
1043 B<IMPORTANT:> If the user has disabled JavaScript in his browser this test will
1044 be never executed. Use a corresponding Perl Regex with C<matches_regex>
1045 to get a server side validation. Use this with care, because different browser
1046 may have different support for regular expressions.
1047  
1048 =item not_matches_regex
1049  
1050 Value must not match B<Perl> regular expression. Only executed on server side.
1051  
1052 =item not_matches_regex_js
1053  
1054 Value must not match B<JavaScript> regular expression. Only executed on client side.
1055 B<IMPORTANT:> If the user has disabled JavaScript in his browser this test will
1056 be never executed. Use a corresponding Perl Regex with C<not_matches_regex>
1057 to get a server side validation. Use this with care, because different browser
1058 may have different support for regular expressions.
1059  
1060 =item matches_wildcard
1061  
1062 =item must_only_contain
1063  
1064 =item must_not_contain
1065  
1066 =item must_contain_one_of
1067  
1068 =item checked
1069  
1070 Checkbox must be selected
1071  
1072 =item notchecked
1073  
1074 Checkbox must not be selected
1075  
1076 =back
1077  
1078  
1079 =head2 PREFERENCES
1080  
1081 The $pref hash (reference) contains information about a single form
1082 request or submission, e.g. the browser version, which made the
1083 request or submission and the language in which the error messages
1084 should be returned. See also L<validate>
1085  
1086  
1087 =head2 ERROR CODES
1088  
1089 For a descriptions of the error codes, validate is returning see L<validate>
1090  
1091  
1092 =head2 FDAT
1093  
1094 See also L<Embperl>.
1095  
1096 my $fdat = { foo => 'foobar',
1097 bar => 'baz',
1098 baz => 49,
1099 fnord => 1.2 };
1100  
1101 =head1 Example
1102  
1103 This example simply validates the form input when you hit submit.
1104 If your input is correct, the form is redisplay with your input,
1105 otherwise the error message is shown. If you turn off JavaScript
1106 the validation is still done one the server-side. Any validation
1107 for which no JavaScript validation is defined (like regex matches),
1108 only the server-side validation is performed.
1109  
1110  
1111 <html>
1112 <head>
1113 [-
1114  
1115 use Embperl::Form::Validate ;
1116  
1117 $epf = Embperl::Form::Validate -> new (
1118 [
1119 [
1120 -key => 'name',
1121 -name => 'Name',
1122 required => 1,
1123 length_min => 4,
1124 ],
1125 [
1126 -key => 'id',
1127 -name => 'Id',
1128 -type => 'Number',
1129 gt => 0,
1130 lt => 10,
1131 ],
1132 [
1133 -key => 'email',
1134 -msg => 'This is not a valid E-Mail address',
1135 must_contain_one_of => '@.',
1136 matches_regex => '..+@..+\\...+',
1137 length_min => 8,
1138 ],
1139 [
1140 -key => 'msg',
1141 -name => 'Message',
1142 emptyok => 1,
1143 length_min => 10,
1144 ]
1145 ]) ;
1146  
1147 if ($fdat{check})
1148 {
1149 $errors = $epf -> validate_messages ;
1150 }
1151  
1152 -]
1153 <script>
1154 [+ do { local $escmode = 0 ; $epf -> get_script_code } +]
1155 </script>
1156 </head>
1157 <body>
1158  
1159 <h1>Embperl Example - Input Form Validation</h1>
1160  
1161 [$if @$errors $]
1162 <h3>Please correct the following errors</h3>
1163 [$foreach $e (@$errors)$]
1164 <font color="red">[+ $e +]</font><br>
1165 [$endforeach$]
1166 [$else$]
1167 <h3>Please enter your data</h3>
1168 [$endif$]
1169  
1170 <form action="formvalidation.htm" method="GET" onSubmit="return epform_validate_forms_0_()">
1171 <table>
1172 <tr><td><b>Name</b></td> <td><input type="text" name="name"></td></tr>
1173 <tr><td><b>Id (1-9)</b></td> <td><input type="text" name="id"></td></tr>
1174 <tr><td><b>E-Mail</b></td> <td><input type="text" name="email"></td></tr>
1175 <tr><td><b>Message</b></td> <td><input type="text" name="msg"></td></tr>
1176 <tr><td colspan=2><input type="submit" name="check" value="send"></td></tr>
1177 </table>
1178 </form>
1179  
1180  
1181 <p><hr>
1182  
1183 <small>Embperl (c) 1997-2010 G.Richter / ecos gmbh <a href="https://www.actevy.io">www.acteviy.io</a></small>
1184  
1185 </body>
1186 </html>
1187  
1188  
1189 See also eg/x/formvalidation.htm
1190  
1191  
1192 =head1 SEE ALSO
1193  
1194 See also L<Embperl>.
1195  
1196 =head1 AUTHOR
1197  
1198 Axel Beckert
1199 Gerald Richter (richter at embperl dot org)
1200