Added postcode validation and test for validators

This commit is contained in:
Tom Bloor 2017-04-09 12:50:50 +01:00
parent 0a32b05b6c
commit 704f429fa5
4 changed files with 50 additions and 8 deletions

View file

@ -4,6 +4,7 @@ requires 'Data::UUID';
requires 'Devel::Dwarn';
requires 'Mojo::JSON';
requires 'Email::Valid';
requires 'Geo::UK::Postcode';
requires 'ORM::Date';
requires 'Authen::Passphrase::BlowfishCrypt';
requires 'Time::Fake';

View file

@ -12,16 +12,17 @@ sub index {
sub register {
my $c = shift;
my $validation = $c->validation;
$validation->required('token')->in_resultset(
'accounttokenname',
$c->schema->resultset('AccountToken')->search_rs({used => 0}),
);
$validation->required('name', 'trim');
$validation->required('email')->email;
$validation->required('agerange')->in_resultset(
'agerangeid',
$c->schema->resultset('AgeRange'),
);
$validation->required('password')->equal_to('password2');
$validation->required('postcode')->postcode;
my $token_rs = $c->schema->resultset('AccountToken')->search_rs({used => 0});
$validation->required('token')->in_resultset('accounttokenname', $token_rs);
my $age_rs = $c->schema->resultset('AgeRange');
$validation->required('agerange')->in_resultset('agerangeid', $age_rs);
use Devel::Dwarn;
Dwarn $validation;

View file

@ -2,6 +2,7 @@ package Pear::LocalLoop::Plugin::Validators;
use Mojo::Base 'Mojolicious::Plugin';
use Email::Valid;
use Geo::UK::Postcode;
sub register {
my ( $plugin, $app, $conf ) = @_;
@ -10,10 +11,16 @@ sub register {
my ( $validation, $name, $email ) = @_;
return Email::Valid->address( $email ) ? undef : 1;
});
$app->validator->add_check( in_resultset => sub {
my ( $validation, $name, $value, $key, $rs ) = @_;
return $rs->search({ $key => $value })->count ? undef : 1;
});
$app->validator->add_check( postcode => sub {
my ( $validation, $name, $value ) = @_;
return Geo::UK::Postcode->new( $value )->valid ? undef : 1;
});
}
1;

33
t/plugins/validators.t Normal file
View file

@ -0,0 +1,33 @@
use strict;
use warnings;
use Mojolicious::Lite;
use Test::More;
plugin 'Pear::LocalLoop::Plugin::Validators';
my $validator = app->validator;
my $validation = $validator->validation;
my $valid_email = 'test@example.com';
my $invalid_email = 'test.example.com';
my $valid_postcode = 'WC1H 9EB';
my $invalid_postcode = 'AB1 2CD';
$validation->input({
valid_email => $valid_email,
invalid_email => $invalid_email,
valid_postcode => $valid_postcode,
invalid_postcode => $invalid_postcode,
});
$validation->required('valid_email')->email;
$validation->required('invalid_email')->email;
$validation->required('valid_postcode')->postcode;
$validation->required('invalid_postcode')->postcode;
ok $validation->has_error, 'Have Errors';
is_deeply $validation->failed, [ 'invalid_email', 'invalid_postcode' ], 'Correct Errors';
done_testing;