Subscribed unsubscribe Subscribe Subscribe

Image::Info を使って FormValidator::Lite::Constraint::File よりもう少し厳し目にチェックする

さん

package MyApp::FormValidator::Constraint::ImageType;

use strict;
use warnings;

use FormValidator::Lite::Constraint;
use Image::Info ();
use Carp ();

file_rule 'IMAGE_TYPE' => sub {
    Carp::croak('missing args. usage: ["IMAGE_TYPE", "(GIF|PNG|JPEG)"]') unless @_;
    my $expected = $_[0];
    my $type = Image::Info::image_type($_->{upload}->path);

    if ( exists $type->{error} ) {
        warn "image_type error: " . $type->{error};
        return undef;
    }
    return $type->{file_type} =~ /^$expected/;
};

1;
use FormValidator::Lite qw(+MyApp::FormValidator::Constraint::ImageType);
my $v = FormValidator::Lite->new($q);
$v->check( photo => [ ['IMAGE_TYPE', 'JPEG'] ] );

みたいな感じで使う

$_->{upload}->path は plack::request::upload だけでしか動かないと思います。