see other projects

Form::Tiny module

Context-independent data validation centered around well-established type checking libraries

Data validation with familiar syntax

Form::Tiny was designed to reuse the bits and pieces of modern Perl programming which are widely used: Moose syntax and Type::Tiny type libraries. The introduced syntax should be familiar enough to Moose programmers to have a very smooth learning curve. It is easily customizable and contains features not observed in other form frameworks, like strict mode which causes any data not explicitly specified in the validator to produce an error.

Example code

use v5.20;

package GuessingGame {
    use Form::Tiny -filtered;
    use Types::Common::Numeric qw(PositiveInt);

    has 'randomed_number' => (
        is => 'ro',
        isa => PositiveInt,
        default => sub { int(rand 99) + 1 },
    );

    form_trim_strings;

    form_field 'guessed_number' => (
        type => PositiveInt,
        required => 1,
    );

    form_hook cleanup => sub {
        my ($self, $data) = @_;

        my $result = $self->randomed_number <=> $data->{guessed_number};

        $self->add_error(
            'you guessed wrong - aim ' . ($result < 0 ? 'lower' : 'higher')
        ) unless $result == 0;
    };
}

my $form = GuessingGame->new;
while (-playing) {
    print 'Guess a number between 1 and 100: ';
    my $guess = <STDIN>;

    $form->set_input({guessed_number => $guess});
    last if $form->valid;

    say 'Invalid guess, because:';
    for my $error ($form->errors->@*) {
        say '  ' . $error->as_string;
    }
}

say 'Congratulations, you guessed right!';

Example output

Guess a number between 1 and 100: no!
Invalid guess, because:
  guessed_number - Must be a positive integer
Guess a number between 1 and 100:
Invalid guess, because:
  guessed_number - does not exist
Guess a number between 1 and 100: 50
Invalid guess, because:
  general - you guessed wrong - aim higher
Guess a number between 1 and 100: 75
Invalid guess, because:
  general - you guessed wrong - aim higher
Guess a number between 1 and 100: 90
Invalid guess, because:
  general - you guessed wrong - aim higher
Guess a number between 1 and 100: 95
Invalid guess, because:
  general - you guessed wrong - aim higher
Guess a number between 1 and 100: 99
Invalid guess, because:
  general - you guessed wrong - aim lower
Guess a number between 1 and 100: 98
Congratulations, you guessed right!