Created
June 20, 2011 12:40
-
-
Save oroce/1035546 to your computer and use it in GitHub Desktop.
parameter validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
my %fields = ( | |
name => { | |
required => 1, | |
test => qr!\w+!, | |
nope => "Name field is required, it shouldn't be empty!" | |
}, | |
bplace => { | |
required => 1, | |
test => qr!\w+!, | |
nope => "Birth place field is required, it shouldn't be empty!" | |
}, | |
bdate => { | |
required => 1, | |
test => qr!^\d{4}-\d{2}-\d{2}$!, | |
cb => sub { | |
my $date = shift; | |
return 0 if !$date; | |
eval{ my $dt = DateTime::Format::ISO8601->parse_datetime( $date ); die if !$dt; }; | |
return $@ ? 0 : 1; | |
}, | |
nope => "Birth date field is required, it shouldn't be empty, format: YYYY-MM-DD" | |
}, | |
sex => { | |
required => 0, | |
test => qr!^m|f$!, | |
nope => "Sex field is required, it shouldn't be empty, Male or Female?" | |
}, | |
agree => { | |
required => 0, | |
nope => "You should agree...", | |
cb => sub{ defined shift; } | |
} | |
); | |
my @warnings = (); | |
my @errors = (); | |
foreach my $f ( keys %fields ){ | |
my $param = $self->param( $f ); | |
my $is_err = 0; | |
if( $fields{ $f }->{test} && $param !~ $fields{ $f }->{test} ){ | |
$is_err = 1; | |
} | |
if( $fields{ $f }->{cb} && !$fields{ $f }->{cb}( $param ) ){ | |
$is_err = 1; | |
} | |
if( $is_err ){ | |
my $resp = { | |
name => $f, | |
value => $param, | |
message => $fields{ $f }->{nope} | |
}; | |
push( @errors, $resp ), next if $fields{ $f }->{required}; | |
push @warnings, $resp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment