package RequestForm::Validate;
use Moo;
use Data::FormValidator;
use Data::Dumper::Concise;
use Data::FormValidator::Constraints qw(:closures);
use LIMS::Local::Utils;
sub validate { # returns hashref containing errs (fail) or data (pass) keys
my $self = shift;
my $vars = shift;
my $defaults = _dfv_defaults();
my $dfv = Data::FormValidator->new({}, $defaults);
my $dfv_profile = dfv_profile(); # DEBUG($dfv_profile);
my $results = $dfv->check($vars, $dfv_profile); # DEBUG($results);
my %h;
if ( $results->has_invalid or $results->has_missing ) { # warn Dumper $results;
$h{errs} = $results->msgs;
}
else {
my $data = $results->valid; # warn Dumper $h{data};
# create dob from day, month & year vals & delete original vals:
my @date_fields = qw(year month day);
$data->{dob} = sprintf '%s-%02d-%02d', @{$data}{@date_fields};
delete $data->{$_} for @date_fields; # warn Dumper $data;
$h{data} = $data;
}
return \%h;
}
sub dfv_profile {
my @required = qw(
last_name first_name nhs_number gender location referrer day month year
specimen diagnosis report_to treatment clinical_details taken_by contact
datetime doi tb previous hb wbc plt
);
my @optional = qw( patient_number sample_ref neut lymph other);
return {
required => \@required,
optional => \@optional,
field_filters => {
last_name => 'uc',
first_name => 'lc',
location => 'lc',
referrer => 'lc',
},
constraint_methods => {
nhs_number => _check_nhs_number(),
year => _check_date(), # or any required date field
},
msgs => {
constraints => { },
},
}
}
sub _dfv_defaults {
return {
missing_optional_valid => 1,
filters => 'trim', # trims white space either side of field param
msgs => {
any_errors => 'dfv_errors', # default err__
format => '<div class="dfv-err text-uppercase">%s</div>',
},
};
}
sub _check_nhs_number {
return sub {
my $dfv = shift; # warn Dumper $dfv;
my $nhs_number = shift || return 0; # warn 'NHSNo:'.$nhs_number;
# check_nhsno() return true if valid:
my $is_valid = LIMS::Local::Utils::check_nhsno( $nhs_number ); # warn $is_valid;
return $is_valid;
};
}
sub _check_date {
return sub {
my $dfv = shift; # warn Dumper $dfv;
my $data = $dfv->get_filtered_data; # warn Dumper $data;
my $date = join '/', @{$data}{qw/day month year/}; # warn $date;
my $is_valid = LIMS::Local::Utils::check_date($date); # warn $is_valid;
return $is_valid;
};
}
1;