Index: t/validators/yaml.t =================================================================== --- t/validators/yaml.t (revision 0) +++ t/validators/yaml.t (revision 0) @@ -0,0 +1,50 @@ +use strict; +use warnings; + +use Test::More tests => 8; + +use HTML::FormFu; + +BEGIN { use_ok('YAML'); } + +my $form = HTML::FormFu->new; + +$form->element('Text')->name('foo')->validator('YAML'); +$form->element('Text')->name('bar')->validator('YAML'); + +# Valid +{ + $form->process( { + foo => "---\ntest:\n - list1: [ item ]\n", + bar => "thing: yes\nstuff: no\n", + } ); + + ok( $form->valid('foo'), 'foo valid' ); + ok( $form->valid('bar'), 'bar valid' ); +} + +# Invalid +{ + my $invalid = 'aaa'; + + $form->process( { + foo => $invalid, + bar => 'foo\n-', + } ); + + ok( !$form->valid('foo'), 'foo not valid' ); + ok( !$form->valid('bar'), 'bar not valid' ); + + my ($error) = @{ $form->get_errors }; + + my $error_msg = 'Invalid YAML'; + eval { YAML::Load($invalid) }; + + if ($@) { + ($error_msg) = ($@ =~ /^(.*?)\n/); + } + + is( $error->class, 'error_validator_yaml' ); + is( $error->type, 'YAML' ); + like( $error->message, qr/^${error_msg}/ ); +} Index: lib/HTML/FormFu/I18N/en.pm =================================================================== --- lib/HTML/FormFu/I18N/en.pm (revision 1009) +++ lib/HTML/FormFu/I18N/en.pm (working copy) @@ -30,6 +30,8 @@ form_inflator_imager => 'Error opening image file', form_validator_imager_size => 'Image upload too large', form_transformer_imager => 'Error processing image file', + + form_validator_yaml => 'Invalid YAML', ); 1; Index: lib/HTML/FormFu/Validator/YAML.pm =================================================================== --- lib/HTML/FormFu/Validator/YAML.pm (revision 0) +++ lib/HTML/FormFu/Validator/YAML.pm (revision 0) @@ -0,0 +1,70 @@ +package HTML::FormFu::Validator::YAML; + +use strict; +use base 'HTML::FormFu::Validator'; + +use YAML qw(Load); + +sub validate_value { + my ( $self, $value ) = @_; + + my $ok = 1; + + eval { my $data = Load($value) }; + + if ($@) { + # Capture first line of stack trace because that's where the error + # message is + my ($msg) = ($@ =~ /^(.*?)\n/); + if ($msg) { + # build validator exception + my $exception = HTML::FormFu::Exception::Validator->new; + $exception->message("$msg"); + die $exception; + } else { + # We couldn't extract an error message from the stack trace, so + # use default i18n error message instead + $ok = 0; + } + } + + return $ok; +} + +1; + +__END__ + +=head1 NAME + +HTML::FormFu::Validator::YAML - YAML validator + +=head1 SYNOPSIS + + $field->validator('YAML'); + + --- + elements: + - type: Text + name: foo + validators: + - type: YAML + +=head1 DESCRIPTION + +YAML validator. + +=head1 SEE ALSO + +Is a sub-class of, and inherits methods from L + +L + +=head1 AUTHOR + +Byron Young C + +=head1 LICENSE + +This library is free software, you can redistribute it and/or modify it under +the same terms as Perl itself.