Apache-Voodoo
view release on metacpan or search on metacpan
lib/Apache/Voodoo/Validate.pm view on Meta::CPAN
sub new {
my $class = shift;
my $config = shift || {};
my $self = {};
bless $self, $class;
$self->{'ef'} = sub {
my ($f,$t,$e) = @_;
$e->{$t.'_'.$f} = 1;
};
$self->_configure($config);
return $self;
}
sub set_valid_callback {
my $self = shift;
#my $context = shift;
my $sub_ref = shift;
#unless (defined($context)) {
# Apache::Vodooo::Exception::RunTime->throw("add_callback requires a context name as the first parameter");
#}
unless (ref($sub_ref) eq "CODE") {
Apache::Vodooo::Exception::RunTime::BadConfig->throw("add_callback requires a subroutine reference as the second paramter");
}
#push(@{$self->{'callbacks'}->{$context}},$sub_ref);
$self->{'vc'} = $sub_ref;
}
sub set_error_formatter {
my $self = shift;
my $sub_ref = shift;
if (ref($sub_ref) eq "CODE") {
$self->{'ef'} = $sub_ref;
}
}
sub required { return map { $_->name } grep { $_->required } @{$_[0]->{fields}} };
sub unique { return map { $_->name } grep { $_->unique } @{$_[0]->{fields}} };
sub multiple { return map { $_->name } grep { $_->multiple } @{$_[0]->{fields}} };
sub fields {
my $self = shift;
my $type = shift;
if ($type) {
return grep { $_->type eq $type } @{$self->{fields}};
}
else {
return @{$self->{fields}};
}
}
sub validate {
my $self = shift;
my $p = shift;
my $values = {};
my $errors = {};
foreach my $field ($self->fields) {
my $good;
my $missing = 1;
my $bad = 0;
foreach ($self->_param($p,$field)) {
next unless defined ($_);
# call the validation routine for each value
my ($v,@b) = $field->valid($_);
if (defined($b[0])) {
# bad one, we're outta here.
$bad = 1;
foreach (@b) {
$self->{'ef'}->($field->{'name'},$_,$errors);
}
last;
}
elsif (defined($field->valid_sub)) {
# there's a validation subroutine, call it
my $r = $field->valid_sub()->($v);
if (defined($r) && $r == 1) {
push(@{$good},$v);
$missing = 0;
}
else {
$bad = 1;
if (!defined($r) || $r == 0) {
$r = 'BAD';
}
$self->{'ef'}->($field->name,$r,$errors);
}
}
elsif (defined($v)) {
push(@{$good},$v);
$missing = 0;
}
}
# check requiredness
if ($missing && $field->required) {
$bad = 1;
$self->{'ef'}->($field->name,'MISSING',$errors);
}
$self->_pack($good,$field,$values) unless ($bad);
}
if ($self->{vc}) {
foreach ($self->{vc}->($values,$errors)) {
next unless ref($_) eq "ARRAY";
$self->{'ef'}->($_->[0],$_->[1],$errors);
( run in 0.542 second using v1.01-cache-2.11-cpan-39bf76dae61 )