blib/lib/CGI/FormBuilder/Field.pm untested

filter: Statementstmt 0.0% 0 / 412 Branchbran 0.0% 0 / 266 Conditioncond 0.0% 0 / 131 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 40 Podpod 0.0% 0 / 34 totaltotal 0.0% 0 / 883 SCAR 98.0
CC
134
Cov
0%
validate
756.0
type
210.0
attr
156.0
CRAP 18090.0
1  
2 ###########################################################################
3 # Copyright (c) Nate Wiger http://nateware.com. All Rights Reserved.
4 # Please visit http://formbuilder.org for tutorials, support, and examples.
5 ###########################################################################
6  
7 package CGI::FormBuilder::Field;
8  
9 =head1 NAME
10  
11 CGI::FormBuilder::Field - Base class for FormBuilder fields
12  
13 =head1 SYNOPSIS
14  
15 use CGI::FormBuilder::Field;
16  
17 # delegated straight from FormBuilder
18 my $f = CGI::FormBuilder::Field->new($form, name => 'whatever');
19  
20 # attribute functions
21 my $n = $f->name; # name of field
22 my $n = "$f"; # stringify to $f->name
23  
24 my $t = $f->type; # auto-type
25 my @v = $f->value; # auto-stickiness
26 my @o = $f->options; # options, aligned and sorted
27  
28 my $l = $f->label; # auto-label
29 my $h = $f->tag; # field XHTML tag (name/type/value)
30 my $s = $f->script; # per-field JS validation script
31  
32 my $m = $f->message; # error message if invalid
33 my $m = $f->jsmessage; # JavaScript error message
34  
35 my $r = $f->required; # required?
36 my $k = $f->validate; # run validation check
37  
38 my $v = $f->tag_value; # value in tag (stickiness handling)
39 my $v = $f->cgi_value; # CGI value if any
40 my $v = $f->def_value; # manually-specified value
41  
42 $f->field(opt => 'val'); # FormBuilder field() call
43  
44 =cut
45  
46 use Carp; # confess used manually in this pkg
47 use strict;
48 use warnings;
49 no warnings 'uninitialized';
50  
51 use CGI::FormBuilder::Util;
52  
53 our $VERSION = '3.10';
54 our $AUTOLOAD;
55  
56 # what to generate for tag
57 our @TAGATTR = qw(name type multiple jsclick);
58  
59 # Catches for special validation patterns
60 # These are semi-Perl patterns; they must be usable by JavaScript
61 # as well so they do not take advantage of features JS can't use
62 # If the value is an arrayref, then the second arg is a tag to
63 # spit out at the person after the field label to help with format
64  
65 our %VALIDATE = (
66 WORD => '/^\w+$/',
67 NAME => '/^[a-zA-Z]+$/',
68 NUM => '/^-?\s*[0-9]+\.?[0-9]*$|^-?\s*\.[0-9]+$/', # 1, 1.25, .25
69 INT => '/^-?\s*[0-9]+$/',
70 FLOAT => '/^-?\s*[0-9]+\.[0-9]+$/',
71 PHONE => '/^\d{3}\-\d{3}\-\d{4}$|^\(\d{3}\)\s+\d{3}\-\d{4}$/',
72 INTPHONE => '/^\+\d+[\s\-][\d\-\s]+$/',
73 EMAIL => '/^[\w\-\+\._]+\@[a-zA-Z0-9][-a-zA-Z0-9\.]*\.[a-zA-Z]+$/',
74 CARD => '/^\d{4}[\- ]?\d{4}[\- ]?\d{4}[\- ]?\d{4}$|^\d{4}[\- ]?\d{6}[\- ]?\d{5}$/',
75 MMYY => '/^(0?[1-9]|1[0-2])\/?[0-9]{2}$/',
76 MMYYYY => '/^(0?[1-9]|1[0-2])\/?[0-9]{4}$/',
77 DATE => '/^(0?[1-9]|1[0-2])\/?(0?[1-9]|[1-2][0-9]|3[0-1])\/?[0-9]{4}$/',
78 EUDATE => '/^(0?[1-9]|[1-2][0-9]|3[0-1])\/?(0?[1-9]|1[0-2])\/?[0-9]{4}$/',
79 TIME => '/^[0-9]{1,2}:[0-9]{2}$/',
80 AMPM => '/^[0-9]{1,2}:[0-9]{2}\s*([aA]|[pP])[mM]$/',
81 ZIPCODE => '/^\d{5}$|^\d{5}\-\d{4}$/',
82 STATE => '/^[a-zA-Z]{2}$/',
83 COUNTRY => '/^[a-zA-Z]{2}$/',
84 IPV4 => '/^([0-1]??\d{1,2}|2[0-4]\d|25[0-5])\.([0-1]??\d{1,2}|2[0-4]\d|25[0-5])\.([0-1]??\d{1,2}|2[0-4]\d|25[0-5])\.([0-1]??\d{1,2}|2[0-4]\d|25[0-5])$/',
85 NETMASK => '/^([0-1]??\d{1,2}|2[0-4]\d|25[0-5])\.([0-1]??\d{1,2}|2[0-4]\d|25[0-5])\.([0-1]??\d{1,2}|2[0-4]\d|25[0-5])\.([0-1]??\d{1,2}|2[0-4]\d|25[0-5])$/',
86 FILE => '/^[\/\w\.\-_]+$/',
87 WINFILE => '/^[a-zA-Z]:\\[\\\w\s\.\-]+$/',
88 MACFILE => '/^[:\w\.\-_]+$/',
89 USER => '/^[-a-zA-Z0-9_]{4,8}$/',
90 HOST => '/^[a-zA-Z0-9][-a-zA-Z0-9]*$/',
91 DOMAIN => '/^[a-zA-Z0-9][-a-zA-Z0-9\.]*\.[a-zA-Z]+$/',
92 ETHER => '/^[\da-f]{1,2}[\.:]?[\da-f]{1,2}[\.:]?[\da-f]{1,2}[\.:]?[\da-f]{1,2}[\.:]?[\da-f]{1,2}[\.:]?[\da-f]{1,2}$/i',
93 # Many thanks to Mark Belanger for these additions
94 FNAME => '/^[a-zA-Z]+[- ]?[a-zA-Z]*$/',
95 LNAME => '/^[a-zA-Z]+[- ]?[a-zA-Z]+\s*,?([a-zA-Z]+|[a-zA-Z]+\.)?$/',
96 CCMM => '/^0[1-9]|1[012]$/',
97 CCYY => '/^[1-9]{2}$/',
98 );
99  
100 # stringify to name
101 use overload '""' => sub { $_[0]->name },
102 #'.' => sub { $_[0]->name },
103 '0+' => sub { $_[0]->name },
104 'bool' => sub { $_[0]->name },
105 'eq' => sub { $_[0]->name eq $_[1] };
106  
107 sub new {
108 puke "Not enough arguments for Field->new()" unless @_ > 1;
109 my $self = shift;
110  
111 my $form = shift; # need for top-level attr
112 my $opt = arghash(@_);
113 $opt->{_form} = $form; # parental ptr
114 puke "Missing name for field() in Field->new()"
115 unless $opt->{name};
116  
117 my $class = ref($self) || $self;
118 my $f = bless $opt, $class;
119  
120 # Note that at this point, the object is a generic field
121 # without a type. Not until it's called via $f->type does
122 # it get a type, which affects its HTML representation.
123 # Everything else is inherited from this module.
124  
125 return $f;
126 }
127  
128 sub field {
129 my $self = shift;
130  
131 if (ref $_[0] || @_ > 1) {
132 my $opt = arghash(@_);
133 while (my($k,$v) = each %$opt) {
134 next if $k eq 'name'; # segfault??
135 $self->{$k} = $v;
136 }
137 }
138 return $self->value; # needed for @v = $form->field('name')
139 }
140  
141 *override = \&force; # CGI.pm
142 sub force {
143 my $self = shift;
144 $self->{force} = shift if @_;
145 return $self->{force} || $self->{override};
146 }
147  
148 # grab the field_other field if other => 1 specified
149 sub other {
150 my $self = shift;
151 $self->{other} = shift if @_;
152 return unless $self->{other};
153 $self->{other} = {} unless ref $self->{other};
154 $self->{other}{name} = $self->othername;
155 return wantarray ? %{$self->{other}} : $self->{other};
156 }
157  
158 sub othername {
159 my $self = shift;
160 return $self->{_form}->othername . '_' . $self->name;
161 }
162  
163 sub othertag {
164 my $self = shift;
165 return '' unless $self->other;
166  
167 # add an additional tag for our _other field
168 my $oa = $self->other; # other attr
169  
170 # default settings
171 $oa->{type} ||= 'text';
172 my $v = $self->{_form}->cgi_param($self->othername);
173 #$v = $self->tag_value unless defined $v;
174 if ($self->sticky and defined $v) {
175 $oa->{value} = $v;
176 }
177  
178 $oa->{disabled} = 'disabled' if $self->javascript && ! defined $v; # fanciness
179 return htmltag('input', $oa);
180 }
181  
182 sub growname {
183 my $self = shift;
184 return $self->{_form}->growname . '_' . $self->name;
185 }
186  
187 sub cgi_value {
188 my $self = shift;
189 debug 2, "$self->{name}: called \$field->cgi_value";
190 puke "Cannot set \$field->cgi_value manually" if @_;
191 if (my @v = $self->{_form}{params}->can('multi_param') ? $self->{_form}{params}->multi_param($self->name) : $self->{_form}{params}->param($self->name)) {
192 for my $v (@v) {
193 if ($self->other && $v eq $self->othername) {
194 debug 1, "$self->{name}: redoing value from _other field";
195 $v = $self->{_form}{params}->param($self->othername);
196 }
197 }
198 local $" = ',';
199 debug 2, "$self->{name}: cgi value = (@v)";
200 return wantarray ? @v : $v[0];
201 }
202 return;
203 }
204  
205 sub def_value {
206 my $self = shift;
207 debug 2, "$self->{name}: called \$field->def_value";
208 if (@_) {
209 $self->{value} = arglist(@_); # manually set
210 delete $self->{_cache}{type}; # clear auto-type
211 }
212 my @v = autodata $self->{value};
213 local $" = ',';
214 debug 2, "$self->{name}: def value = (@v)";
215 $self->inflate_value(\@v);
216 return wantarray ? @v : $v[0];
217 }
218  
219 sub inflate_value {
220 my ($self, $v_aref) = @_;
221  
222 debug 2, "$self->{name}: called \$field->inflate_value";
223  
224 # trying to inflate?
225 return unless exists $self->{inflate};
226 debug 2, "$self->{name}: inflate routine exists";
227  
228 # must return real values to the validate() routine:
229 return if grep { ((caller($_))[3] eq 'CGI::FormBuilder::Field::validate') }
230 1..2;
231 debug 2, "$self->{name}: made sure inflate not called via validate";
232  
233 # must be valid:
234 #return unless exists $self->{invalid} && ! $self->{invalid};
235 return if $self->invalid;
236 debug 2, "$self->{name}: valid field, inflate proceeding";
237  
238 my $cache = $self->{inflated_values};
239  
240 if ($cache && ref $cache eq 'ARRAY' && @{$cache}) {
241 # could have been cached by validate() check
242 @{ $v_aref } = @{ $self->{inflated_values} };
243 debug 2, "$self->{name}: using cached inflate "
244 . "value from validate()";
245 }
246 else {
247 debug 2, "$self->{name}: new inflate";
248  
249 puke("Field $self->{name}: inflate must be a reference to a \\&sub")
250 if ref $self->{inflate} ne 'CODE';
251  
252 eval { @{ $v_aref } = map $self->{inflate}->($_), @{ $v_aref } };
253  
254 # no choice but to die hard if didn't validate() first
255 puke("Field $self->{name}: inflate failed: $@") if $@;
256  
257 # cache the result:
258 @{ $self->{inflated_values} } = @{ $v_aref };
259 }
260 return;
261 }
262  
263 # CGI.pm happiness
264 *default = \&value;
265 *defaults = \&value;
266 *values = \&value;
267 sub value {
268 my $self = shift;
269 debug 2, "$self->{name}: called \$field->value(@_)";
270 if (@_) {
271 $self->{value} = arglist(@_); # manually set
272 delete $self->{_cache}{type}; # clear auto-type
273 }
274 unless ($self->force) {
275 # CGI wins if stickiness is set
276 debug 2, "$self->{name}: sticky && ! force";
277 if (my @v = $self->cgi_value) {
278 local $" = ',';
279 debug 1, "$self->{name}: returning value (@v)";
280 $self->inflate_value(\@v);
281 return wantarray ? @v : $v[0];
282 }
283 }
284 debug 2, "no cgi found, returning def_value";
285 # no CGI value, or value was forced, or not sticky
286 return $self->def_value;
287 }
288  
289 # The value in the <tag> may be different than in code (sticky)
290 sub tag_value {
291 my $self = shift;
292 debug 2, "$self->{name}: called \$field->tag_value";
293 if (@_) {
294 # setting the tag_value manually is odd...
295 $self->{tag_value} = arglist(@_);
296 delete $self->{_cache}{type};
297 }
298 return $self->{tag_value} if $self->{tag_value};
299  
300 if ($self->sticky && ! $self->force) {
301 # CGI wins if stickiness is set
302 debug 2, "$self->{name}: sticky && ! force";
303 if (my @v = $self->cgi_value) {
304 local $" = ',';
305 debug 1, "$self->{name}: returning value (@v)";
306 return wantarray ? @v : $v[0];
307 }
308 }
309 debug 2, "no cgi found, returning def_value";
310 # no CGI value, or value was forced, or not sticky
311 return $self->def_value;
312 }
313  
314 # Handle "b:select" and "b:option"
315 sub tag_name {
316 my $self = shift;
317 $self->{tag_name} = shift if @_;
318 return $self->{tag_name} if $self->{tag_name};
319 # Try to guess
320 my($tag) = ref($self) =~ /^CGI::FormBuilder::Field::(.+)/;
321 puke "Can't resolve tag for untyped field '$self->{name}'"
322 unless $tag;
323 return $tag;
324 }
325  
326 sub type {
327 local $^W = 0; # -w sucks
328 my $self = shift;
329 if (@_) {
330 $self->{type} = lc shift;
331 delete $self->{_cache}{type}; # forces rebless
332 debug 2, "setting field type to '$self->{type}'";
333 }
334  
335 #
336 # catch for new way of saying static => 1
337 #
338 # confirm() will set ->static but not touch $self->{type},
339 # so make sure it's not a field the user hid themselves
340 #
341 if ($self->static && $self->{type} ne 'hidden') {
342 $self->{type} = 'static';
343 delete $self->{_cache}{type}; # forces rebless
344 debug 2, "setting field type to '$self->{type}'";
345 }
346  
347 # manually set
348 debug 2, "$self->{name}: called \$field->type (manual = '$self->{type}')";
349  
350 # The $field->type method is called so often that it really slows
351 # things down. As such, we cache the type and use it *unless* the
352 # value has been updated manually (we assume one CGI instance).
353 # See value() for its deletion of this cache
354 return $self->{_cache}{type} if $self->{_cache}{type};
355  
356 my $name = $self->{name};
357 my $type;
358 unless ($type = lc $self->{type}) {
359 #
360 # Unless the type has been set explicitly, we make a guess
361 # based on how many items there are to display, which is
362 # basically, how many options we have. Our 'jsclick' option
363 # is now changed down in the javascript section, fixing a bug
364 #
365 if ($self->{_form}->smartness) {
366 debug 1, "$name: input type not set, checking for options";
367 if (my $n = $self->options) {
368 debug 2, "$name: has options, so setting to select|radio|checkbox";
369 if ($n >= $self->selectnum) {
370 debug 2, "$name: has more than selectnum (", $self->selectnum,
371 ") options, setting to 'select'";
372 $type = 'select';
373 } else {
374 # Something is a checkbox if it is a multi-valued box.
375 # However, it is *also* a checkbox if only single-valued options,
376 # otherwise you can't unselect it.
377 my @v = $self->def_value; # only on manual, not dubious CGI
378 if ($self->multiple || @v > 1 || $n == 1) {
379 debug 2, "$name: has multiple select < selectnum, setting to 'checkbox'";
380 $type = 'checkbox';
381 } else {
382 debug 2, "$name: has singular select < selectnum, setting to 'radio'";
383 $type = 'radio';
384 }
385 }
386 } elsif ($self->{_form}->smartness > 1) {
387 debug 2, "$name: smartness > 1, auto-inferring type based on value";
388 # only autoinfer field types based on values with high smartness
389 my @v = $self->def_value; # only on manual, not dubious CGI
390 if ($name =~ /passw(or)?d/i) {
391 $type = 'password';
392 } elsif ($name =~ /(?:details?|comments?)$/i
393 || grep /\n|\r/, @v || $self->cols || $self->rows) {
394 $type = 'textarea';
395 } elsif ($name =~ /\bfile/i) {
396 $type = 'file';
397 }
398 } else {
399 debug 2, "no options found";
400 }
401 }
402 $type ||= 'text'; # default if no fancy settings matched or no smartness
403 }
404 debug 1, "$name: field set to type '$type' (reblessing)";
405  
406 # Store type in cache for speediness
407 $self->{_cache}{type} = $type;
408  
409 # Re-bless into the appropriate package
410 my $pkg = __PACKAGE__ . '::' . $type;
411 $pkg =~ s/\-/_/g; # handle HTML5 type names ala 'datetime-local'
412 eval "require $pkg";
413 puke "Can't load $pkg for field '$name' (type '$type'): $@" if $@;
414 bless $self, $pkg;
415  
416 return $type;
417 }
418  
419 sub label {
420 my $self = shift;
421 $self->{label} = shift if @_;
422 return $self->{label} if defined $self->{label}; # manually set
423 return toname($self->name);
424 }
425  
426 sub attr {
427 my $self = shift;
428 if (my $k = shift) {
429 $self->{$k} = shift if @_;
430 return exists $self->{$k} ? $self->{$k} : $self->{_form}->$k;
431 } else {
432 # exhaustive expansion, but don't invoke validate().
433 my %ret;
434 for my $k (@TAGATTR, keys %$self) {
435 my $v;
436 next if $k =~ /^_/ || $k eq 'validate'; # don't invoke validate
437 if ($k eq 'jsclick') {
438 # always has to be a special fucking case
439 $v = $self->{$k};
440 $k = $self->jstype;
441 } elsif (exists $self->{$k}) {
442 # flat val
443 $v = $self->{$k};
444 $v = lc $v if $k eq 'type';
445 } else {
446 $v = $self->$k;
447 }
448 next unless defined $v;
449  
450 debug 3, "$self->{name}: \$attr{$k} = '$v'";
451 $ret{$k} = $v;
452 }
453  
454 # More special cases
455 # 1. disabled field/form
456 $self->disabled ? $ret{disabled} = 'disabled'
457 : delete $ret{disabled};
458  
459 # 2. setup class for stylesheets and JS vars
460 $ret{class} ||= $self->{_form}->class('_'.
461 ($ret{type} eq 'text' ? 'input' : $ret{type})
462 );
463  
464 # 3. useless in all tags
465 delete $ret{value};
466  
467 return wantarray ? %ret : \%ret;
468 }
469 }
470  
471 sub multiple {
472 my $self = shift;
473 if (@_) {
474 $self->{multiple} = shift; # manually set
475 delete $self->{_cache}{type}; # clear auto-type
476 }
477 return 'multiple' if $self->{multiple}; # manually set
478 my @v = $self->tag_value;
479 return 'multiple' if @v > 1;
480 return;
481 }
482  
483 sub options {
484 my $self = shift;
485 if (@_) {
486 $self->{options} = shift; # manually set
487 delete $self->{_cache}{type}; # clear auto-type
488 }
489 return unless $self->{options};
490  
491 # align options per internal settings
492 my @opt = optalign($self->{options});
493  
494 # scalar is just counting length, so skip sort
495 return @opt unless wantarray;
496  
497 # sort if requested
498 @opt = optsort($self->sortopts, @opt) if $self->sortopts;
499  
500 return @opt;
501 }
502  
503 # per-field messages
504 sub message {
505 my $self = shift;
506 $self->{message} = shift if @_;
507 my $mess = $self->{message};
508 unless ($mess) {
509 my $type = shift || $self->type;
510 my $et = 'form_invalid_' . ($type eq 'text' ? 'input' : $type);
511 $et = 'form_invalid_input' if $self->other; # other fields assume text
512 $mess = sprintf(($self->{_form}{messages}->$et
513 || $self->{_form}{messages}->form_invalid_default), $self->label);
514 }
515 return $self->{_form}{stylesheet}
516 ? qq(<span class="$self->{_form}{styleclass}_message">$mess</span>)
517 : $mess;
518 }
519  
520 sub jsmessage {
521 my $self = shift;
522 $self->{jsmessage} = shift if @_;
523 my $mess = $self->{jsmessage} || $self->{message};
524 unless ($mess) {
525 my $type = shift || $self->type;
526 my $et = 'js_invalid_' . ($type eq 'text' ? 'input' : $type);
527 $et = 'js_invalid_input' if $self->other; # other fields assume text
528 $mess = sprintf(($self->{_form}{messages}->$et
529 || $self->{_form}{messages}->js_invalid_default),
530 $self->label);
531 }
532 return $mess
533 }
534  
535 sub comment {
536 my $self = shift;
537 $self->{comment} = shift if @_;
538 my $mess = $self->{comment} || return '';
539 return $self->{_form}{stylesheet}
540 ? qq(<span class="$self->{_form}{styleclass}_comment">$mess</span>)
541 : $mess;
542 }
543  
544 # simple error wrapper (why wasn't this here?)
545 sub error {
546 my $self = shift;
547 return $self->invalid ? $self->message : '';
548 }
549  
550 sub jstype {
551 my $self = shift;
552 my $type = shift || $self->type;
553 return ($type eq 'radio' || $type eq 'checkbox') ? 'onclick' : 'onchange';
554 }
555  
556 sub script {
557 my $self = shift;
558 #
559 # An unfortunate hack. Sometimes (often?) we don't know the field
560 # type until render(), in which Javascript is generated first. So,
561 # the grandfather (this) of all script() methods just sets the type
562 # by calling $self->type in a void context (which reblesses the object)
563 # and then calling $self->script again. I think this sucks, but then
564 # again this code shouldn't be called that often. Maybe.
565 #
566 $self->type;
567 $self->script;
568 }
569  
570 sub jsfield {
571 my $self = shift;
572 my $name = $self->name;
573 my $pattern = $self->{validate};
574 debug 2, "return '' unless ".$self->javascript." && ($pattern || ".$self->required.")";
575 return '' unless $self->javascript && ($pattern || $self->required);
576  
577 # First arg is the script that our children should've included
578 my($jsfunc, $close_brace, $in) = @_;
579 unless ($jsfunc) {
580 belch "Missing generated \$jsfunc string for $name->jsfield";
581 return '';
582 }
583  
584 debug 1, "$name: generating JavaScript validation code";
585  
586 # Special catch, since many would assume this would work
587 if (ref $pattern eq 'Regexp') {
588 puke "To use a regex in a 'validate' option you must specify ".
589 "it in single quotes, like '/^\\w+\$/' - failed on '$name' field";
590 }
591  
592 # hashref is a grouping per-language
593 if (ref $pattern eq 'HASH') {
594 $pattern = $pattern->{javascript} || return '';
595 }
596  
597 # Check our hash to see if it's a special pattern
598 $pattern = $VALIDATE{$pattern} if $VALIDATE{$pattern};
599  
600 # Make field name JS-safe
601 my $jsfield = tovar($name);
602  
603 # Note we have to use form.elements['name'] instead of just form.name
604 # as the JAPH using this module may have defined fields like "u.type"
605 my $alertstr = escapejs($self->jsmessage); # handle embedded '
606 $alertstr .= '\n';
607  
608 # Our fields are only required if the required option is set
609 # So, if not set, add a not-null check to the if below
610 my $notnull = $self->required
611 ? qq[$jsfield == null ||] # must have or error
612 : qq[$jsfield != null && $jsfield != "" &&]; # only care if filled in
613  
614 if ($pattern =~ m#^m?(\S)(.*)\1$#) {
615 # JavaScript regexp
616 ($pattern = $2) =~ s/\\\//\//g;
617 $pattern =~ s/\//\\\//g;
618 $jsfunc .= qq[${in}if ($notnull ! $jsfield.match(/$pattern/)) {\n];
619 }
620 elsif (ref $pattern eq 'ARRAY') {
621 # Must be w/i this set of values
622 # Can you figure out how this piece of Perl works? No, seriously, I forgot.
623 $jsfunc .= qq[${in}if ($notnull ($jsfield != ']
624 . join("' && $jsfield != '", @{$pattern}) . "')) {\n";
625 }
626 elsif (ref $pattern eq 'CODE' || $pattern eq 'VALUE' || ($self->required && ! $pattern)) {
627 # Not null (for required sub refs, just check for a value)
628 $jsfunc .= qq[${in}if ($notnull $jsfield === "") {\n];
629 }
630 else {
631 # Literal string is literal code to execute, but provide
632 # a warning just in case
633 belch "Validation string '$pattern' may be a typo of a builtin pattern"
634 if $pattern =~ /^[A-Z]+$/;
635 $jsfunc .= qq[${in}if ($notnull $jsfield $pattern) {\n];
636 }
637  
638 # add on our alert message, but only if it's required
639 $jsfunc .= <<EOJS;
640 $in alertstr += '$alertstr';
641 $in invalid++;
642 $in invalid_fields.push('$jsfield');
643 $in}$close_brace
644 EOJS
645  
646 return $jsfunc;
647 }
648  
649 *render = \&tag;
650 sub tag {
651 my $self = shift;
652 $self->type;
653 return $self->tag(@_);
654 }
655  
656 sub validate () {
657  
658 # This function does all the validation on the Perl side.
659 # It doesn't generate JavaScript; see render() for that...
660  
661 my $self = shift;
662 my $form = $self->{_form}; # alias for examples (paint-by-numbers)
663 local $^W = 0; # -w sucks
664  
665 my $pattern = shift || $self->{validate};
666 my $field = $self->name;
667  
668 # inflation subref?
669 my $inflate = (exists $self->{inflate}) ? $self->{inflate} : undef;
670 puke("$field: inflate attribute must be subroutine reference")
671 if defined $inflate && ref $inflate ne 'CODE';
672 puke("$field: inflate requires a validation pattern")
673 if defined $inflate && !defined $pattern;
674 $self->{inflated_values} = [ ] if $inflate;
675  
676 debug 1, "$self->{name}: called \$field->validate(@_) for field '$field'";
677  
678 # Check our hash to see if it's a special pattern
679 ($pattern) = autodata($VALIDATE{$pattern}) if $VALIDATE{$pattern};
680  
681 # Hashref is a grouping per-language
682 if (ref $pattern eq 'HASH') {
683 $pattern = $pattern->{perl} || return 1;
684 }
685  
686 # Counter for fail or success
687 my $bad = 0;
688  
689 # Loop thru, and if something isn't valid, we tag it
690 my $atleastone = 0;
691 $self->{invalid} ||= 0;
692 for my $value ($self->value) {
693 my $thisfail = 0;
694  
695 # only continue if field is required or filled in
696 if ($self->required) {
697 debug 1, "$field: is required per 'required' param";
698 } else {
699 debug 1, "$field: is optional per 'required' param";
700 next unless length($value) && defined($pattern);
701 debug 1, "$field: ...but is defined, so still checking";
702 }
703  
704 $atleastone++;
705 debug 1, "$field: validating ($value) against pattern '$pattern'";
706  
707 if ($pattern =~ m#^m(\S)(.*)\1$# || $pattern =~ m#^(/)(.*)\1$#) {
708 # it be a regexp, handle / escaping
709 (my $tpat = $2) =~ s#\\/#/#g;
710 $tpat =~ s#/#\\/#g;
711 debug 2, "$field: does '$value' =~ /$tpat/ ?";
712 unless ($value =~ /$tpat/) {
713 $thisfail = ++$bad;
714 }
715 } elsif (ref $pattern eq 'ARRAY') {
716 # must be w/i this set of values
717 debug 2, "$field: is '$value' in (@{$pattern}) ?";
718 unless (ismember($value, @{$pattern})) {
719 $thisfail = ++$bad;
720 }
721 } elsif (ref $pattern eq 'CODE') {
722 # eval that mofo, which gives them $form
723 my $extra = $form->{c} || $form;
724 debug 2, "$field: does $pattern($value, $extra) ret true ?";
725 unless (&{$pattern}($value, $extra)) {
726 $thisfail = ++$bad;
727 }
728 } elsif ($pattern eq 'VALUE') {
729 # Not null
730 debug 2, "$field: length '$value' > 0 ?";
731 unless (defined($value) && length($value)) {
732 $thisfail = ++$bad;
733 }
734 } elsif (! defined $pattern) {
735 debug 2, "$field: length('$value') > 0";
736 $thisfail = ++$bad unless length($value) > 0;
737 } else {
738 # literal string is a literal comparison, but warn of typos...
739 belch "Validation string '$pattern' may be a typo of a builtin pattern"
740 if ($pattern =~ /^[A-Z]+$/);
741 # must reference to prevent serious problem if $value = "'; system 'rm -f /'; '"
742 debug 2, "$field: '$value' $pattern ? 1 : 0";
743 unless (eval qq(\$value $pattern ? 1 : 0)) {
744 $thisfail = ++$bad;
745 }
746 belch "Literal code eval error in validate: $@" if $@;
747 }
748  
749 # Just for debugging's sake
750 $thisfail ? debug 2, "$field: pattern FAILED"
751 : debug 2, "$field: pattern passed";
752
753 # run inflation subref if defined, trap errors and warn
754 if (defined $inflate) {
755 debug 1, "trying to inflate value '$value'";
756 my $inflated_value = eval { $inflate->($value) };
757 if ($@) {
758 belch "Field $field: inflate failed on value '$value' due to '$@'";
759 $thisfail = ++$bad;
760 }
761 # cache for value():
762 push @{$self->{inflated_values}}, $inflated_value;
763  
764 # debugging:
765 $thisfail ? debug 2, "$field: inflate FAILED"
766 : debug 2, "$field: inflate passed";
767 }
768 }
769  
770 # If not $atleastone and they asked for validation, then we
771 # know that we have an error since this means no values
772 if ($bad || (! $atleastone && $self->required)) {
773 debug 1, "$field: validation FAILED";
774 $self->{invalid} = $bad || 1;
775 $self->{missing} = $atleastone;
776 return;
777 } else {
778 debug 1, "$field: validation passed";
779 delete $self->{invalid}; # in case of previous run
780 delete $self->{missing}; # ditto
781 return 1;
782 }
783 }
784  
785 sub static () {
786 my $self = shift;
787 $self->{static} = shift if @_;
788 return $self->{static} if exists $self->{static};
789 # check parent for this as well
790 return $self->{_form}{static};
791 }
792  
793 sub disabled () {
794 my $self = shift;
795 $self->{disabled} = shift if @_;
796 return ($self->{disabled} ? 'disabled' : undef)
797 if exists $self->{disabled};
798 # check parent for this as well
799 return $self->{_form}->disabled;
800 }
801  
802 sub javascript () {
803 my $self = shift;
804 $self->{javascript} = shift if @_;
805 return $self->{javascript} if exists $self->{javascript};
806 # check parent for this as well
807 return $self->{_form}{javascript};
808 }
809  
810 sub growable () {
811 my $self = shift;
812 $self->{growable} = shift if @_;
813 return unless $self->{growable};
814 # check to make sure we're only a text or file type
815 unless ($self->type eq 'text' || $self->type eq 'file') {
816 belch "The 'growable' option only works with 'text' or 'file' fields";
817 return;
818 }
819 return $self->{growable};
820 }
821  
822 sub name () {
823 my $self = shift;
824 $self->{name} = shift if @_;
825 confess "[".__PACKAGE__."::name] Fatal: Attempt to manipulate unnamed field"
826 unless exists $self->{name};
827 return $self->{name};
828 }
829  
830 sub DESTROY { 1 }
831  
832 sub AUTOLOAD {
833 # This allows direct addressing by name, for quicker usage
834 my $self = shift;
835 my($name) = $AUTOLOAD =~ /.*::(.+)/;
836  
837 debug 3, "-> dispatch to \$field->{$name} = @_";
838 croak "self not ref in AUTOLOAD" unless ref $self; # nta
839  
840 $self->{$name} = shift if @_;
841 return $self->{$name};
842 }
843  
844 1;
845 __END__