From 286ecf11e1d074b5526866394065567b5b583eba Mon Sep 17 00:00:00 2001 From: Tom Bloor Date: Tue, 25 Apr 2017 20:50:34 +0100 Subject: [PATCH] Fixed issue with validator for postcodes --- cpanfile | 1 + lib/Pear/LocalLoop/Plugin/Validators.pm | 8 +++++++- t/plugins/validators.t | 5 ++++- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/cpanfile b/cpanfile index 4d40bc6..a363a30 100644 --- a/cpanfile +++ b/cpanfile @@ -16,3 +16,4 @@ requires 'SQL::Translator'; requires 'DateTime'; requires 'DateTime::Format::Strptime', "1.73"; requires 'DateTime::Format::SQLite'; +requires 'Try::Tiny'; diff --git a/lib/Pear/LocalLoop/Plugin/Validators.pm b/lib/Pear/LocalLoop/Plugin/Validators.pm index 8dfaf4e..eb2ebbb 100644 --- a/lib/Pear/LocalLoop/Plugin/Validators.pm +++ b/lib/Pear/LocalLoop/Plugin/Validators.pm @@ -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 { diff --git a/t/plugins/validators.t b/t/plugins/validators.t index 596cdad..60027b3 100644 --- a/t/plugins/validators.t +++ b/t/plugins/validators.t @@ -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;