Fixed issue with validator for postcodes

This commit is contained in:
Tom Bloor 2017-04-25 20:50:34 +01:00
parent e31ec73934
commit 286ecf11e1
3 changed files with 12 additions and 2 deletions

View file

@ -16,3 +16,4 @@ requires 'SQL::Translator';
requires 'DateTime';
requires 'DateTime::Format::Strptime', "1.73";
requires 'DateTime::Format::SQLite';
requires 'Try::Tiny';

View file

@ -6,6 +6,7 @@ use Geo::UK::Postcode;
use Scalar::Util qw/ looks_like_number /;
use File::Basename qw/ fileparse /;
use DateTime::Format::Strptime;
use Try::Tiny;
sub register {
my ( $plugin, $app, $conf ) = @_;
@ -27,7 +28,12 @@ sub register {
$app->validator->add_check( postcode => sub {
my ( $validation, $name, $value ) = @_;
return Geo::UK::Postcode->new( $value )->valid ? undef : 1;
my $postcode;
try {
$postcode = Geo::UK::Postcode->new( $value );
};
return defined $postcode && $postcode->valid ? undef : 1;
});
$app->validator->add_check( number => sub {

View file

@ -14,20 +14,23 @@ my $valid_email = 'test@example.com';
my $invalid_email = 'test.example.com';
my $valid_postcode = 'WC1H 9EB';
my $invalid_postcode = 'AB1 2CD';
my $not_a_postcode = 'a';
$validation->input({
valid_email => $valid_email,
invalid_email => $invalid_email,
valid_postcode => $valid_postcode,
invalid_postcode => $invalid_postcode,
not_a_postcode => $not_a_postcode,
});
$validation->required('valid_email')->email;
$validation->required('invalid_email')->email;
$validation->required('valid_postcode')->postcode;
$validation->required('invalid_postcode')->postcode;
$validation->required('not_a_postcode')->postcode;
ok $validation->has_error, 'Have Errors';
is_deeply $validation->failed, [ 'invalid_email', 'invalid_postcode' ], 'Correct Errors';
is_deeply $validation->failed, [ qw/ invalid_email invalid_postcode not_a_postcode / ], 'Correct Errors';
done_testing;