Data::Validator(3pm)

πŸ“¦ version 1.07, in alpine 3.24

πŸ’– Data::Validator πŸ’–

okay bestie, gather round, because this is the User Contributed Perl Documentation page for Data::Validator, and it's genuinely a little icon. it's a rule-based validator built on a type constraint system, and yes, we're gonna get into every single detail together. no cap. 🫢

✨ NAME ✨

Data::Validator β€” rule based validator on type constraint system. that's the whole vibe: you make rules, it validates your data. slay. πŸ’…

🌸 VERSION 🌸

this doc describes Data::Validator version 1.07. noted, memorized, moving on. πŸŽ€

πŸ¦‹ SYNOPSIS πŸ¦‹

here's the whole flex, verbatim, because copying code wrong is a crime and i don't do crimes:

    use 5.10.0;
    use Data::Validator;

    # for functions
    sub get {
        state $rule = Data::Validator->new(
            uri        => { isa => 'Str', xor => [qw(schema host path_query)] },

            schema     => { isa => 'Str', default => 'http' },
            host       => { isa => 'Str' },
            path_query => { isa => 'Str', default => '/' },

            method     => { isa => 'Str', default => 'GET' },
        );

        my $args = $rule->validate(@_);
        # ...
    }
    get( uri => 'http://example.com/' );

    # for methods
    sub method {
        state $rule = Data::Validator->new(
            foo => 'Str',
        )->with('Method');

        my($self, $args) = $rule->validate(@_);
        # ...
    }
    Foo->method( foo => 'bar' );

    # using sequenced parameters
    sub seq {
        state $rule = Data::Validator->new(
            foo => 'Str',
        )->with('StrictSequenced');

        my $args = $rule->validate(@_);
        # ...
    }
    seq( 'bar' );          # seq() will get { foo => 'bar' }
    seq({ foo => 'bar' }); # named style are NOT available!

    # using Method and StrictSequenced together
    sub seq_method {
        state $rule = Data::Validator->new(
            foo => 'Str',
        )->with( 'Method', 'StrictSequenced');

        my($self, $args) = $rule->validate(@_);
        # ...
    }
    Foo->seq_method( 'bar' ); # seq_method() will get { foo => 'bar' }

    # using sequenced and named parameters
    sub smart_seq {
        my $rule = Data::Validator->new(
            r1 => 'Str',
            r2 => 'HashRef',  # accept this
            o1 => { isa => 'Str', default => 'yes' },
            o2 => { isa => 'Num', optional => 1 },
        )->with('SmartSequenced');

        my $args = $rule->validate(@_);
        # ...
    }

    # all will get { r1 => 'foo', r2 => { val => 'bar' }, o1 => 'yes' }

    # mixed style(recommend)
    smart_seq( 'foo', { val => 'bar' }, { o1 => 'yes' } );
    smart_seq( 'foo', { val => 'bar' } );

    # also accept sequenced style
    smart_seq( 'foo', { val => 'bar' }, 'yes' );
    smart_seq( 'foo', { val => 'bar' } );

    # also accept named style
    smart_seq( { r1 => 'foo', r2 => { val => 'bar' }, o1 => 'yes' } );
    smart_seq( { r1 => 'foo', r2 => { val => 'bar' } } );

like, look at all those styles. it's giving versatility. it's giving main character energy. 🌈

πŸ‘‘ DESCRIPTION πŸ‘‘

so this is yet another validation library, based on Smart::Args but less smart. and honestly? that's the design choice. it's built for general data validation, so think CSV, JSON, XML, and honestly whatever else you're throwing at it.

πŸ’œ Concepts πŸ’œ

🌸 Natural as Perl code 🌸

the author loves Smart::Args because it's really stylish, but it does not seem Perl-ish. so Data::Validator was designed in a more Perl-ish way, with full Smart::Args functionality. best of both worlds, tbh.

πŸ¦‹ Basics on type constraint system πŸ¦‹

Moose's type constraint system is awesome, and so is Mouse's. in fact, Mouse's type constraints are much faster than Moose's, so you need not hesitate to check types. that's why Data::Validator is made on Mouse's type constraint system. fast and pretty. obsessed. ✨

πŸŽ€ Pure Perl πŸŽ€

the author doesn't hesitate to depend on XS modules, but some people think XS modules are hard to install. so Data::Validator is written in pure Perl, and it picks dependent modules that work in pure Perl. inclusive king behavior. 🫢

⭐ Performance ⭐

validators should be as fast as possible because they matter only for illegal inputs. otherwise, one would want something like a no validation option. this one is much faster than Params::Validate, which has an XS backend, though. okay wig. πŸ”₯

πŸ’… INTERFACE πŸ’…

πŸ“ Data::Validator->new( $arg_name => $rule [, ...]) :Validator

creates a validation rule. you should cache the rules for performance. (say it with me: cache the rules.)

attributes for $rule are as follows:

  • isa => $type : Str|Object β€” the type of the rule, which can be a Mouse type constraint name, a class name, or a type constraint object of either Mouse or Moose (i.e. it's duck-typed). duck typing my beloved. πŸ¦†
  • does => $role : Str|Object β€” the type of the rule, which can be a Mouse type constraint name, a role name, or a type constraint object of either Mouse or Moose (i.e. it's duck-typed).
note that you cannot use it with the isa attribute. they do not coexist bestie, that's the rule. πŸ™ˆ
  • coerce => $should_coercion : Bool β€” if false, the rule does not try to coerce when the validation fails. default to true. so by default, it will try. okay!
  • default=> $value : Any | CodeRef β€” the default value for the argument. if it is a CODE reference, it is called in scalar context as $default->($validator, $rule, $args) and its return value is used as a default value.

because arguments are validated in the order of definitions, default callbacks can rely on the previously-filled values:

    my $v = Data::Validator->new(
        foo => { default => 99 },
        bar => { default => sub {
            my($validator, $this_rule, $args) = @_;
            return $args->{foo} + 1;
        } },
    );
    $v->validate();          # bar is 100
    $v->validate(foo => 42); # bar is 43

unlike Moose/Mouse's default, any references are allowed, but note that they are statically allocated. that's a detail bestie, don't skip it.

  • optional => $value : Bool β€” if true, users can omit the argument. default to false.
  • xor => $exclusives : ArrayRef β€” exclusive arguments, which users cannot pass together. pick one, not both. periodt. 🚫
  • documentation => $doc : Str β€” descriptions of the argument.
this is not yet used anywhere. literally just sitting there. pretty, though. πŸŽ€

🌟 $validator->find_rule($name :Str)

finds the rule named $name. provided for error handling. that's it, that's the whole thing. πŸ’–

🌈 $validator->with(@extensions) :Validator

applies @extensions to $validator and returns itself. see EXTENSIONS for details. chainable, iconic. ✨

πŸ’€ $validator->validate(@args) :HashRef

validates @args and returns a restricted HASH reference.

restricted hashes are hashes which do not allow to access non-existing keys, so you must check a key exists in the hash before fetching its values. do not skip the exists check, bestie. not me warning you twice. 😭

🧚 EXTENSIONS 🧚

there are extensions which change behaviours of validate().

  • Method β€” takes the first argument as an invocant (i.e. class or object instance), and returns it as the first value:
    my($invocant, $args) = $rule->validate(@_);
  • SmartSequenced β€” deals with arguments in mixing sequenced style and named style. the sequenced style should be passed by the order of argument rules, and the named style arguments should be the last argument as HASH ref.

the typical usage is that the required arguments as sequenced style, and some optional arguments as named style. smart indeed. 🧠

  • StrictSequenced β€” deals with arguments in sequenced style, where users should pass arguments by the order of argument rules, instead of by-name.
note that single HASH ref argument was dealt as named-style arguments, but this feature is NOT available since version 1.01. it is gone, bestie. do not expect it. πŸ’€
  • Sequenced β€” deals with arguments in sequenced style, where users should pass arguments by the order of argument rules, instead of by-name.
note that if the last argument is a HASH reference, it is regarded as named-style arguments. that one is available here.
  • AllowExtra β€” regards unknown arguments as extra arguments, and returns them as a list of name-value pairs:
    my($args, %extra) = $rule->validate(@_);
  • NoThrow β€” does not throw errors. instead, it provides validators with the errors attribute:
    my $args = $v->validate(@_); # it never throws errors
    if($v->has_errors) {
        my $errors = $v->clear_errors;
        foreach my $e(@{$errors}) {
            # $e has 'type', 'message' and 'name'
            print $e->{message}, "\n";
        }
    }

no drama, just errors in an attribute. very demure. πŸ’…

  • Croak β€” does not report stack backtrace on errors, i.e. uses croak() instead of confess() to throw errors.
  • NoRestricted β€” does not make the argument hash restricted. freedom for the hash. πŸ¦‹

πŸŽ€ DEPENDENCIES πŸŽ€

Perl 5.8.1 or later. that's the floor, bestie. ⭐

πŸ™ˆ BUGS πŸ™ˆ

all complex software has bugs lurking in it, and this module is no exception. if you find a bug please either email me, or add the bug to cpan-RT. no shame, just report it. 🫢

🌸 SEE ALSO 🌸

  • Smart::Args
  • Params::Validate
  • Sub::Args
  • MooseX::Params::Validate
  • Mouse
  • Hash::Util for a restricted hash.

the whole friend group, right there. πŸ‘‘

πŸ’– AUTHOR πŸ’–

Fuji, Goro (gfx) <gfuji@cpan.org>. legend behavior. 🌟

Copyright (c) 2010, Fuji Goro (gfx). All rights reserved.

this library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


okay that's the whole page bestie, every last detail, no skips, no cap. this one came from perl v5.42.2 and it's dated 2023-07-03, so jot that down and go validate something cute. mwah. πŸ’œβœ¨

πŸ“¦ where this page comes from