Validate-Tiny

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

Revision history for Validate-Tiny

1.6     2016-11-08
	[Changes]
	POD fixes (DJERIUS)

1.551   2015-05-08

        [Bug fixes]
        Fix is_a constraint stringification issue

        [New features]
        Add is_existing constraint

        [Other]
        Return success with bare return instead of return undef

1.501   2015-04-18 !!! Not backwards compatible. Read notes !!!
        
        [Bug fixes]
        - filters checked for undefined values

        [New features]
        - A new %FILTER hash allows a user to add custom filters
        - Object interface changed - new is now just a constructor and
          check is used to do actual validation. To adapt your code,
          it should be enough to just replace all Validate::Tiny->new with
          Validate::Tiny->check.
        - Removed error_string function

1.015   2015-02-21
        Code refactoring

0.105   2014-04-04
        Out of beta. Stable release.
        No code changes.

0.982   2012-07-09
        Replaced "defined" with "exists" to allow filtering of keys
        with undef value.
        Added a third param to check subs $key, which contains the
        name of the fields being checked.

0.982   2012-05-08
        Fix a bug with $vt->data croaking if no input fields are
        specified.

0.981   2012-04-26
        Empty fields array will now process all input fields

0.98    2012-02-01
        Fix whitespace glitch in filter 'strip'.
        Move tests to different files.
        Write more tests.

0.38    2012-01-25
        Added dependancy info in META

0.37    2012-01-20
        Add is_required_if closure

0.35    2012-01-16
        Fix stock closure logic when handling not-required fields.
        Test not only if the value is defined, but also if it is
        an empty value.

0.32    2012-01-12
        Ge back to using List::MoreUtils and Exporter
        (under pressure from reddit users)

0.31    2012-01-11
        Add credits in POD

0.30    2011-01-10
        Lower minimum required Perl version to 5.8
        add is_a, is_like, is_in constraint closures

0.21    2011-12-09
        Add "single" parameter to method "error_string".
        Fix typos and enhance POD.

0.20    2011-12-08
        Add method error_string

0.10    2011-12-08
        Typos in POD fixed.

0.09    2011-10-07
        Update Test::More dependency to 0.94 (needed for subtest)
        Remove dependency from List::MoreUtils

0.08    2011-09-17
        Fixed croak issue with missing fields
        Add undef checks

0.06    2011-07-25
        Add object interface

0.05    2011-07-22
        Edit meta files

0.01    2011-07-01
        First version, released.

LICENSE  view on Meta::CPAN

This software is copyright (c) 2016 by Stefan G.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

Terms of the Perl programming language system itself

a) the GNU General Public License as published by the Free
   Software Foundation; either version 1, or (at your option) any
   later version, or
b) the "Artistic License"

--- The GNU General Public License, Version 1, February 1989 ---

This software is Copyright (c) 2016 by Stefan G.

This is free software, licensed under:

  The GNU General Public License, Version 1, February 1989

                    GNU GENERAL PUBLIC LICENSE
                     Version 1, February 1989

 Copyright (C) 1989 Free Software Foundation, Inc.
 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The license agreements of most software companies try to keep users
at the mercy of those companies.  By contrast, our General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  The
General Public License applies to the Free Software Foundation's
software and to any other program whose authors commit to using it.
You can use it for your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Specifically, the General Public License is designed to make
sure that you have the freedom to give away or sell copies of free
software, that you receive source code or can get it if you want it,
that you can change the software or use pieces of it in new free
programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of a such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must tell them their rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  The precise terms and conditions for copying, distribution and
modification follow.

                    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License Agreement applies to any program or other work which
contains a notice placed by the copyright holder saying it may be
distributed under the terms of this General Public License.  The
"Program", below, refers to any such program or work, and a "work based
on the Program" means either the Program or any work containing the
Program or a portion of it, either verbatim or with modifications.  Each
licensee is addressed as "you".

  1. You may copy and distribute verbatim copies of the Program's source
code as you receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice and
disclaimer of warranty; keep intact all the notices that refer to this
General Public License and to the absence of any warranty; and give any
other recipients of the Program a copy of this General Public License
along with the Program.  You may charge a fee for the physical act of
transferring a copy.

  2. You may modify your copy or copies of the Program or any portion of
it, and copy and distribute such modifications under the terms of Paragraph
1 above, provided that you also do the following:

    a) cause the modified files to carry prominent notices stating that
    you changed the files and the date of any change; and

    b) cause the whole of any work that you distribute or publish, that
    in whole or in part contains the Program or any part thereof, either
    with or without modifications, to be licensed at no charge to all
    third parties under the terms of this General Public License (except
    that you may choose to grant warranty protection to some or all
    third parties, at your option).

    c) If the modified program normally reads commands interactively when
    run, you must cause it, when started running for such interactive use
    in the simplest and most usual way, to print or display an
    announcement including an appropriate copyright notice and a notice
    that there is no warranty (or else, saying that you provide a
    warranty) and that users may redistribute the program under these
    conditions, and telling the user how to view a copy of this General
    Public License.

    d) You may charge a fee for the physical act of transferring a
    copy, and you may at your option offer warranty protection in
    exchange for a fee.

Mere aggregation of another independent work with the Program (or its
derivative) on a volume of a storage or distribution medium does not bring
the other work under the scope of these terms.

  3. You may copy and distribute the Program (or a portion or derivative of
it, under Paragraph 2) in object code or executable form under the terms of
Paragraphs 1 and 2 above provided that you also do one of the following:

    a) accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of
    Paragraphs 1 and 2 above; or,

    b) accompany it with a written offer, valid for at least three
    years, to give any third party free (except for a nominal charge
    for the cost of distribution) a complete machine-readable copy of the
    corresponding source code, to be distributed under the terms of
    Paragraphs 1 and 2 above; or,

    c) accompany it with the information you received as to where the
    corresponding source code may be obtained.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form alone.)

Source code for a work means the preferred form of the work for making
modifications to it.  For an executable file, complete source code means
all the source code for all modules it contains; but, as a special
exception, it need not include source code for modules which are standard
libraries that accompany the operating system on which the executable
file runs, or for standard header files or definitions files that
accompany that operating system.

  4. You may not copy, modify, sublicense, distribute or transfer the
Program except as expressly provided under this General Public License.
Any attempt otherwise to copy, modify, sublicense, distribute or transfer
the Program is void, and will automatically terminate your rights to use
the Program under this License.  However, parties who have received
copies, or rights to use copies, from you under this General Public
License will not have their licenses terminated so long as such parties
remain in full compliance.

  5. By copying, distributing or modifying the Program (or any work based
on the Program) you indicate your acceptance of this license to do so,
and all its terms and conditions.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the original
licensor to copy, distribute or modify the Program subject to these
terms and conditions.  You may not impose any further restrictions on the
recipients' exercise of the rights granted herein.

  7. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of the license which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
the license, you may choose any version ever published by the Free Software
Foundation.

  8. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

                            NO WARRANTY

  9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

                     END OF TERMS AND CONDITIONS

        Appendix: How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to humanity, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.

  To do so, attach the following notices to the program.  It is safest to
attach them to the start of each source file to most effectively convey
the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) 19yy  <name of author>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 1, or (at your option)
    any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA  02110-1301 USA


Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) 19xx name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the
appropriate parts of the General Public License.  Of course, the
commands you use may be called something other than `show w' and `show
c'; they could even be mouse-clicks or menu items--whatever suits your
program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the
  program `Gnomovision' (a program to direct compilers to make passes
  at assemblers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

That's all there is to it!


--- The Artistic License 1.0 ---

This software is Copyright (c) 2016 by Stefan G.

This is free software, licensed under:

  The Artistic License 1.0

The Artistic License

Preamble

The intent of this document is to state the conditions under which a Package
may be copied, such that the Copyright Holder maintains some semblance of
artistic control over the development of the package, while giving the users of
the package the right to use and distribute the Package in a more-or-less
customary fashion, plus the right to make reasonable modifications.

Definitions:

  - "Package" refers to the collection of files distributed by the Copyright
    Holder, and derivatives of that collection of files created through
    textual modification. 
  - "Standard Version" refers to such a Package if it has not been modified,
    or has been modified in accordance with the wishes of the Copyright
    Holder. 
  - "Copyright Holder" is whoever is named in the copyright or copyrights for
    the package. 
  - "You" is you, if you're thinking about copying or distributing this Package.
  - "Reasonable copying fee" is whatever you can justify on the basis of media
    cost, duplication charges, time of people involved, and so on. (You will
    not be required to justify it to the Copyright Holder, but only to the
    computing community at large as a market that must bear the fee.) 
  - "Freely Available" means that no fee is charged for the item itself, though
    there may be fees involved in handling the item. It also means that
    recipients of the item may redistribute it under the same conditions they
    received it. 

1. You may make and give away verbatim copies of the source form of the
Standard Version of this Package without restriction, provided that you
duplicate all of the original copyright notices and associated disclaimers.

2. You may apply bug fixes, portability fixes and other modifications derived
from the Public Domain or from the Copyright Holder. A Package modified in such
a way shall still be considered the Standard Version.

3. You may otherwise modify your copy of this Package in any way, provided that
you insert a prominent notice in each changed file stating how and when you
changed that file, and provided that you do at least ONE of the following:

  a) place your modifications in the Public Domain or otherwise make them
     Freely Available, such as by posting said modifications to Usenet or an
     equivalent medium, or placing the modifications on a major archive site
     such as ftp.uu.net, or by allowing the Copyright Holder to include your
     modifications in the Standard Version of the Package.

  b) use the modified Package only within your corporation or organization.

  c) rename any non-standard executables so the names do not conflict with
     standard executables, which must also be provided, and provide a separate
     manual page for each non-standard executable that clearly documents how it
     differs from the Standard Version.

  d) make other distribution arrangements with the Copyright Holder.

4. You may distribute the programs of this Package in object code or executable
form, provided that you do at least ONE of the following:

  a) distribute a Standard Version of the executables and library files,
     together with instructions (in the manual page or equivalent) on where to
     get the Standard Version.

  b) accompany the distribution with the machine-readable source of the Package
     with your modifications.

  c) accompany any non-standard executables with their corresponding Standard
     Version executables, giving the non-standard executables non-standard
     names, and clearly documenting the differences in manual pages (or
     equivalent), together with instructions on where to get the Standard
     Version.

  d) make other distribution arrangements with the Copyright Holder.

5. You may charge a reasonable copying fee for any distribution of this
Package.  You may charge any fee you choose for support of this Package. You
may not charge a fee for this Package itself. However, you may distribute this
Package in aggregate with other (possibly commercial) programs as part of a
larger (possibly commercial) software distribution provided that you do not
advertise this Package as a product of your own.

6. The scripts and library files supplied as input to or produced as output
from the programs of this Package do not automatically fall under the copyright
of this Package, but belong to whomever generated them, and may be sold
commercially, and may be aggregated with this Package.

7. C or perl subroutines supplied by you and linked into this Package shall not
be considered part of this Package.

8. The name of the Copyright Holder may not be used to endorse or promote
products derived from this software without specific prior written permission.

9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.

The End

MANIFEST  view on Meta::CPAN

# This file was automatically generated by Dist::Zilla::Plugin::Manifest v6.008.
Changes
LICENSE
MANIFEST
META.yml
Makefile.PL
README.md
dist.ini
lib/Validate/Tiny.pm
t/00-load.t
t/01-filters.t
t/02-checks.t
t/021-undef.t
t/022-key.t
t/03-arrays.t
t/04-oop.t
t/05-sanity.t
t/author-pod-syntax.t
t/checks/01-is_required.t
t/checks/02-is_required_if.t
t/checks/03-is_equal.t
t/checks/04-is_long.t
t/checks/05-is_a.t
t/checks/06-is_like.t
t/checks/07-is_in.t
t/checks/09-is_existing.t
t/filters/01-trim.t
t/filters/02-strip.t
t/filters/03-case.t
t/filters/04-custom.t
t/subs/01-match.t
t/subs/02-filter.t

META.yml  view on Meta::CPAN

---
abstract: 'Minimalistic data validation'
author:
  - 'Stefan G. <minimal@cpan.org>'
build_requires:
  Test::More: 0
configure_requires:
  ExtUtils::MakeMaker: 0
dynamic_config: 0
generated_by: 'Dist::Zilla version 6.008, CPAN::Meta::Converter version 2.150010'
license: perl
meta-spec:
  url: http://module-build.sourceforge.net/META-spec-v1.4.html
  version: 1.4
name: Validate-Tiny
requires:
  Carp: 0
  Exporter: 0
  List::MoreUtils: 0
  strict: 0
  warnings: 0
resources:
  homepage: https://github.com/naturalist/Validate--Tiny
  repository: https://github.com/naturalist/Validate--Tiny.git
version: 1.6
x_serialization_backend: 'YAML::Tiny version 1.51'

Makefile.PL  view on Meta::CPAN

# This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v6.008.
use strict;
use warnings;



use ExtUtils::MakeMaker;

my %WriteMakefileArgs = (
  "ABSTRACT" => "Minimalistic data validation",
  "AUTHOR" => "Stefan G. <minimal\@cpan.org>",
  "CONFIGURE_REQUIRES" => {
    "ExtUtils::MakeMaker" => 0
  },
  "DISTNAME" => "Validate-Tiny",
  "LICENSE" => "perl",
  "NAME" => "Validate::Tiny",
  "PREREQ_PM" => {
    "Carp" => 0,
    "Exporter" => 0,
    "List::MoreUtils" => 0,
    "strict" => 0,
    "warnings" => 0
  },
  "TEST_REQUIRES" => {
    "Test::More" => 0
  },
  "VERSION" => "1.6",
  "test" => {
    "TESTS" => "t/*.t t/checks/*.t t/filters/*.t t/subs/*.t"
  }
);


my %FallbackPrereqs = (
  "Carp" => 0,
  "Exporter" => 0,
  "List::MoreUtils" => 0,
  "Test::More" => 0,
  "strict" => 0,
  "warnings" => 0
);


unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) {
  delete $WriteMakefileArgs{TEST_REQUIRES};
  delete $WriteMakefileArgs{BUILD_REQUIRES};
  $WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs;
}

delete $WriteMakefileArgs{CONFIGURE_REQUIRES}
  unless eval { ExtUtils::MakeMaker->VERSION(6.52) };

WriteMakefile(%WriteMakefileArgs);

README.md  view on Meta::CPAN

# NAME

Validate::Tiny - Minimalistic data validation

# SYNOPSIS

Filter and validate user input from forms, etc.

    use Validate::Tiny ':all';

    my $rules = {

        # List of fields to look for
        fields => [qw/name email pass pass2 gender/],

        # Filters to run on all fields
        filters => [

            # Remove spaces from all
            qr/.+/ => filter(qw/trim strip/),

            # Lowercase email
            email => filter('lc'),

            # Remove non-alphanumeric symbols from
            # both passwords
            qr/pass?/ => sub {
                $_[0] =~ s/\W/./g;
                $_[0];
            },
        ],

        # Checks to perform on all fields
        checks => [

            # All of these are required
            [qw/name email pass pass2/] => is_required(),

            # pass2 must be equal to pass
            pass2 => is_equal('pass'),

            # custom sub validates an email address
            email => sub {
                my ( $value, $params ) = @_;
                return if Email::Valid->address($value);
                return 'Invalid email';
            },

            # custom sub to validate gender
            gender => sub {
                my ( $value, $params ) = @_;
                return if $value eq 'M' || $value eq 'F';
                return 'Invalid gender';
            }

        ]
    };

    # Validate the input agains the rules
    my $result = validate( $input, $rules );

    if ( $result->{success} ) {
        my $values_hash = $result->{data};
        ...
    }
    else {
        my $errors_hash = $result->{error};
        ...
    }

Or if you prefer an OOP approach:

    use Validate::Tiny;

    my $v = Validate::Tiny->new( %args );
    $v->check( $input, $rules );

    if ( $v->success ) {
        my $values_hash = $v->data;
        my $name        = $v->data('name');
        my $email       = $v->data('email');
        ...;
    }
    else {
        my $errors_hash = $v->error;
        my $name_error  = $v->error('name');
        my $email_error = $v->error('email');
    }

# DESCRIPTION

This module provides a simple, light and minimalistic way of validating
user input. Except perl core modules and some test modules it has no other
dependencies, which is why it does not implement any complicated checks
and filters such as email and credit card matching. The basic idea of this
module is to provide the validation functionality, and leave it up to the
user to write their own data filters and checks. If you need a complete
data validation solution that comes with many ready features, I recommend
you to take a look at [Data::FormValidator](https://metacpan.org/pod/Data::FormValidator). If your validation logic is
not too complicated or your form is relatively short, this module is a
decent candidate for your project.

# LOGIC

The basic principle of data/form validation is that any user input must be
sanitized and checked for errors before used in the logic of the program.
Validate::Tiny breaks this process in three steps:

1. Specify the fields you want to work with via ["fields"](#fields).  All others will
be disregarded.
2. Filter the fields' values using ["filters"](#filters). A filter can be as simple as
changing to lower case or removing excess white space, or very complicated
such as parsing and removing HTML tags.
3. Perform a series of ["checks"](#checks) on the filtered values, to make sure they
match the requirements. Again, the checks can be very simple as in
checking if the value was defined, or very complicated as in checking if
the value is a valid credit card number.

The validation returns a hash ref which contains `success` => 1|0,
`data` and `error` hashes. If success is 1, `data` will contain the
filtered values, otherwise `error` will contain the error messages for
each field.

# EXPORT

This module does not automatically export anything. You can optionally
request any of the below subroutines or use ':all' to export all.

# RULES

Rules provide the specifications for the three step validation
process.  They are represented as a hash, containing references to the
following three arrays: ["fields"](#fields), ["filters"](#filters) and ["checks"](#checks).

    my %rules = (
        fields  => \@field_names,
        filters => \@filters_array,
        checks  => \@checks_array
    );

## fields

An array containing the names of the fields that must be filtered, checked
and returned. All others will be disregarded. As of version 0.981 you can
use an empty array for `fields`, which will work on all input fields.

    my @field_names = qw/username email password password2/;

or

    my @field_names = ();   # Use all input fields

## filters

An array containing name matches and filter subs. The array must have an
even number of elements. Each _odd_ element is a field name match and
each _even_ element is a reference to a filter subroutine or a chain of
filter subroutines. A filter subroutine takes one parameter - the value to
be filtered, and returns the modified value.

    my @filters_array = (
        email => sub { return lc $_[0] },    # Lowercase the email
        password =>
          sub { $_[0] =~ s/\s//g; $_[0] }    # Remove spaces from password
    );

The field name is matched with the perl smart match operator, so you could
have a regular expression or a reference to an array to match several
fields:

    my @filters_array = (
        qr/.+/ => sub { lc $_[0] },    # Lowercase ALL

        [qw/password password2/] => sub {    # Remove spaces from both
            $_[0] =~ s/\s//g;                # password and password2
            $_[0];
        }
    );

Instead of a single filter subroutine, you can pass an array of
subroutines to provide a chain of filters:

    my @filters_array = (
        qr/.+/ => [ sub { lc $_[0] }, sub { ucfirst $_[0] } ]
    );

The above example will first lowercase the value then uppercase its first
letter.

Some simple text filters are provided by the ["filter()"](#filter) subroutine.

    use Validate::Tiny qw/validate :util/;

    my @filters_array = (
        name => filter(qw/strip trim lc/)
    );

### Adding custom filters

This module exposes `our %FILTERS`, a hash containing available filters.
To add a filter, add a new key-value to this hash:

    $Validate::Tiny::FILTERS{only_digits} = sub {
        my $val = shift // return;
        $val =~ s/\D//g;
        return $val;
    };

### Filter Support Routines

#### filter

    filter( $name1, $name2, ... );

Provides a shortcut to some basic text filters. In reality, it returns a
list of anonymous subs, so the following:

    my $rules = {
        filters => [
            email => filter('lc', 'ucfirst')
        ]
    };

is equivalent to this:

    my $rules = {
        filters => [
            email => [ sub{ lc $_[0] }, sub{ ucfirst $_[0] } ]
        ]
    };

It provides a shortcut for the following filters:

- trim

    Removes leading and trailing white space.

- strip

    Shrinks two or more white spaces to one.

- lc

    Lower case.

- uc

    Upper case.

- ucfirst

    Upper case first letter

## checks

An array ref containing name matches and check subs. The array must have
an even number of elements. Each _odd_ element is a field name match and
each _even_ element is a reference to a check subroutine or a chain of
check subroutines.

A check subroutine takes three parameters - the value to be checked, a
reference to the filtered input hash and a scalar with the name of the
checked field.

**Example:**

    checks => [
        does_exist => sub {
            my ( $value, $params, $keys ) = @_;
            return "Key doesn't exist in input data"
              unless exists( $params->{$key} );
        }
    ]

A check subroutine must return undef if the check passes or a scalar containing
an error message if the check fails.  The message is not interpreted by
Validate::Tiny, so may take any form, e.g. a string, a reference to
an error object, etc.

**Example:**

    # Make sure the password is good
    sub is_good_password {
        my ( $value, $params ) = @_;

        if ( !defined $value or $value eq '' ) {
            return;
        }

        if ( length($value) < 6 ) {
            return "The password is too short";
        }

        if ( length($value) > 40 ) {
            return "The password is too long";
        }

        if ( $value eq $params->{username} ) {
            return "Your password can not be the same as your username";
        }

        # At this point we're happy with the password
        return;
    }

    my $rules = {
        fields => [qw/username password/],
        checks => [
            password => \&is_good_password
        ]
    };

It may be a bit counter-intuitive for some people to return undef when the
check passes and an error message when it fails. If you have a huge problem with
this concept, then this module may not be right for you.

**Important!** Notice that in the beginning of `is_good_password` we check
if `$value` is defined and return undef if it is not. This is because it
is not the job of `is_good_password` to check if `password` is required.
Its job is to determine if the password is good. Consider the following
example:

    # Password is required and it must pass the check for good password
    #
    my $rules = {
        fields => [qw/username password/],
        checks => [
            password => [ is_required(), \&is_good_password ]
        ]
    };

and this one too:

    # Password is not required, but if it's provided then
    # it must pass the is_good_password constraint.
    #
    my $rules = {
        fields => [qw/username password/],
        checks => [
            username => is_required(),
            password => \&is_good_password
        ]
    };

The above examples show how we make sure that `password` is defined and
not empty before we check if it is a good password.  Of course we can
check if `password` is defined inside `is_good_password`, but it would
be redundant. Also, this approach will fail if `password` is not
required, but must pass the rules for a good password if provided.

### Chaining

The above example also shows that chaining check subroutines is available
in the same fashion as chaining filter subroutines.  The difference
between chaining filters and chaining checks is that a chain of filters
will always run **all** filters, and a chain of checks will exit after the
first failed check and return its error message.  This way the
`$result->{error}` hash always has a single error message per field.

### Using closures

When writing reusable check subroutines, sometimes you will want to be
able to pass arguments. Returning closures (anonymous subs) is the
recommended approach:

    sub is_long_between {
        my ( $min, $max ) = @_;
        return sub {
            my $value = shift;
            return if length($value) >= $min && length($value) <= $max;
            return "Must be between $min and $max symbols";
        };
    }

    my $rules = {
        fields => qw/password/,
        checks => [
            password => is_long_between( 6, 40 )
        ]
    };

### Check Support Routines

Validate::Tiny provides a number of predicates to simplify writing
rules.  They may be passed an optional error message.  Like those
returned by custom check routines, the message is not interpreted by
Validate::Tiny, so may take any form, e.g. a string, a reference to an
error object, etc.

#### is\_required

    is_required( $optional_error_message );

`is_required` provides a shortcut to an anonymous subroutine that
checks if the matched field is defined and it is not an empty
string.
Optionally, you can provide a custom error message. The default is the string,  _Required_.

#### is\_required\_if

    is_required_if( $condition, $optional_error_message );

Require a field conditionally. The condition can be either a scalar or a
code reference that returns true/false value. If the condition is a code
reference, it will be passed the `$params` hash with all filtered fields.
Optionally, you can provide a custom error message. The default is the string,  _Required_.

Example:

    my $rules = {
        fields => [qw/country state/],
        checks => [
            country => is_required(),
            state   => is_required_if(
                sub {
                    my $params = shift;
                    return $params->{country} eq 'USA';
                },
                "Must select a state if you're in the USA"
            )
        ]
    };

Second example:

    our $month = 'October';
    my $rules = {
        fields => ['mustache'],
        checks => [
            mustache => is_required_if(
                $month eq 'October',
                "You must grow a mustache this month!"
            )
        ]
    };

#### is\_existing

    is_existing( $optional_error_message );

Much like `is_required`, but checks if the field contains any value, even an
empty string and `undef`.
Optionally, you can provide a custom error message. The default is the string,  _Must be defined_.

#### is\_equal

    is_equal( $other_field_name, $optional_error_message );

`is_equal` checks if the value of the matched field is the same as the
value of another field within the input hash.
Optionally, you can provide a custom error message. The default is the string,  _Invalid value_.

Example:

    my $rules = {
        checks => [
            password2 => is_equal("password", "Passwords don't match")
        ]
    };

#### is\_long\_between

    is_long_between( $min, $max, $optional_error_message );

Checks if the length of the value is >= `$min` and <= `$max`. Optionally
you can provide a custom error message. The default is the string,  _Invalid value_.

Example:

    my $rules = {
        checks => [
            username => is_long_between( 6, 25, 'Bad username' )
        ]
    };

#### is\_long\_at\_least

    is_long_at_least( $length, $optional_error_message );

Checks if the length of the value is >= `$length`. Optionally you can
provide a custom error message. The default is the string,  _Must be at least %i
symbols_.

Example:

    my $rules = {
        checks => [
            zip_code => is_long_at_least( 5, 'Bad zip code' )
        ]
    };

#### is\_long\_at\_most

    is_long_at_most( $length, $optional_error_message );

Checks if the length of the value is <= `$length`. Optionally you can
provide a custom error message. The default is the string,  _Must be at the most %i
symbols_.

Example:

    my $rules = {
        checks => [
            city_name => is_long_at_most( 40, 'City name is too long' )
        ]
    };

#### is\_a

    is_a ( $class, $optional_error_message );

Checks if the value is an instance of a class. This can be particularly
useful, when you need to parse dates or other user input that needs to get
converted to an object. Since the filters get executed before checks, you
can use them to instantiate the data, then use `is_a` to check if you got
a successful object.
Optionally you can provide a custom error message. The default is the string,  _Invalid value_.

Example:

    use DateTime::Format::Natural;
    use Try::Tiny;

    my $parser = DateTime::Format::Natural->new;

    my $rules = {
        fields  => ['date'],

        filters => [
            date => sub {
                try {
                    $parser->parse_datetime( $_[0] );
                }
                catch {
                    $_[0]
                }
            }
        ],

        checks => [
            date => is_a("DateTime", "Ivalid date")
        ]
    };

#### is\_like

    is_like ( $regexp, $optional_error_message );

Checks if the value matches a regular expression.
Optionally you can provide a custom error message. The default is the string,  _Invalid value_.

Example:

    my $rules = {
        checks => [
            username => is_like( qr/^[a-z0-9_]{6,20}$/, "Bad username" )
        ]
    };

#### is\_in

    is_in ( $arrayref, $optional_error_message );

Checks if the value matches a set of values.
Optionally you can provide a custom error message. The default is the string,  _Invalid value_.

    Example:

    my @cities = qw/Alchevsk Kiev Odessa/;
    my $rules = {
        checks => [
            city => is_in( \@cities, "We only deliver to " . join(',', @cities))
        ]
    };

# PROCEDURAL INTERFACE

## validate

    use Validate::Tiny qw/validate/;

    my $result = validate( \%input, \%rules );

Validates user input against a set of rules. The input is expected to be a
reference to a hash.

### Return value

`validate` returns a hash ref with three elements:

    my $result = validate(\%input, \%rules);

    # Now $result looks like this
    $result = {
        success => 1,       # or 0 if checks didn't pass
        data    => \%data,
        error   => \%error
    };

If `success` is 1 all of the filtered input will be in `%data`,
otherwise the error messages will be stored in `%error`. If `success` is
0, `%data` may or may not contain values, but its use is not recommended.

# OBJECT INTERFACE

## new( %args )

At this point the only argument you can use in `%args` is `filters`,
which should be a hashref with additional filters to be added to the
`%FILTERS` hash.

    my $v = Validate::Tiny->new(
        filters => {
            only_digits => sub {
                my $val = shift // return;
                $val =~ s/\D//g;
                return $val;
            }
        }
    );

## check( \\%input, %rules )

Checks the input agains the rules and initalized internal result state.

    my %input = ( bar => 'abc' );
    my %rules = ( fields => ['bar'], filters => filter('uc') );
    $v->check( \%input, \%rules );

    if ( $v->success ) {
        ...;
    }

## success

Returns a true value if the input passed all the rules.

## data

Returns a hash reference to all filtered fields. If called with a
parameter, it will return the value of that field or croak if there is no
such field defined in the fields array.

    my $all_fields = $result->data;
    my $email      = $result->data('email');

## error

Returns a hash reference to all error messages. If called with a
parameter, it will return the error message of that field, or croak if
there is no such field.

    my $errors = $result->error;
    my $email = $result->error('email');

## to\_hash

Return a result hash, much like using the procedural interface. See the
output of ["validate"](#validate) for more information.

# I18N

A check function is considered failing if it returns a value. In the above
examples we showed you how to return error strings. If you want to
internationalize your errors, you can make your check closures return
[Locale::Maketext](https://metacpan.org/pod/Locale::Maketext) functions, or any other i18n values.

# SEE ALSO

[Data::FormValidator](https://metacpan.org/pod/Data::FormValidator)

# BUGS

Bug reports and patches are welcome. Reports which include a failing
Test::More style test are helpful and will receive priority.

You may also fork the module on Github:
https://github.com/naturalist/Validate--Tiny

# AUTHOR

    Stefan G. (cpan: MINIMAL) - minimal@cpan.org

# CONTRIBUTORS

    Viktor Turskyi (cpan: KOORCHIK) - koorchik@cpan.org
    Ivan Simonik (cpan: SIMONIKI) - simoniki@cpan.org
    Daya Sagar Nune (cpan: DAYANUNE) - daya.webtech@gmail.com
    val - valkoles@gmail.com
    Patrice Clement (cpan: MONSIEURP) - monsieurp@gentoo.org
    Graham Ollis (cpan: PLICEASE)
    Diab Jerius (cpan DJERIUS)

# LICENCE

This program is free software; you can redistribute it and/or modify it
under the terms as perl itself.

dist.ini  view on Meta::CPAN

name  = Validate-Tiny
abstract = Minimalistic data validation

[@Basic]
[AutoPrereqs]
[VersionFromModule]
[ReadmeFromPod]

[PodSyntaxTests]

[GithubMeta]

lib/Validate/Tiny.pm  view on Meta::CPAN

package Validate::Tiny;

use strict;
use warnings;

use Carp;
use Exporter;
use List::MoreUtils 'natatime';

our @ISA = qw/Exporter/;
our @EXPORT_OK = qw/
    validate
    filter
    is_required
    is_required_if
    is_existing
    is_equal
    is_long_between
    is_long_at_least
    is_long_at_most
    is_a
    is_like
    is_in
/;

our %EXPORT_TAGS = (
    'all' => \@EXPORT_OK
);

our $VERSION = '1.6';

our %FILTERS = (
    trim    => sub { return unless defined $_[0]; $_[0] =~ s/^\s+//; $_[0] =~ s/\s+$//; $_[0]  },
    strip   => sub { return unless defined $_[0]; $_[0] =~ s/(\s){2,}/$1/g; $_[0] },
    lc      => sub { return unless defined $_[0]; lc $_[0] },
    uc      => sub { return unless defined $_[0]; uc $_[0] },
    ucfirst => sub { return unless defined $_[0]; ucfirst $_[0] },
);

sub validate {
    my ( $input, $rules ) = @_;
    my $error = {};

    # Sanity check
    #
    die 'You must define a fields array' unless defined $rules->{fields};

    for (qw/filters checks/) {
        next unless exists $rules->{$_};
        if ( ref( $rules->{$_} ) ne 'ARRAY' || @{ $rules->{$_} } % 2 ) {
            die "$_ must be an array with an even number of elements";
        }
    }

    for ( keys %$rules ) {
        /^(fields|filters|checks)$/ or die "Unknown key $_";
    }

    my $param = {};
    my @fields = @{ $rules->{fields} } ? @{ $rules->{fields} } : keys(%$input);

    # Add existing, filtered input to $param
    #
    for my $key ( @fields ) {
        exists $input->{$key} and ($param->{$key} = _process( $rules->{filters}, $input, $key ));
    }

    # Process all checks for $param
    #
    for my $key ( @fields ) {
        my $err = _process( $rules->{checks}, $param, $key, 1 );
        $error->{$key} ||= $err if $err;
    }

    return {
        success => keys %$error ? 0 : 1,
        error   => $error,
        data    => $param
    };

}

sub _run_code {
    my ( $code, $value, $param, $key ) = @_;
    my $result = $value;
    my $ref = ref $code;
    if ( $ref eq 'CODE' ) {
        $result = $code->( $value, $param, $key );
        $value = $result unless defined $param;
    }
    elsif ( $ref eq 'ARRAY' ) {
        for (@$code) {
            $result = _run_code( $_, $value, $param, $key );
            if ( defined $param ) {
                last if $result;
            }
            else {
                $value = $result;
            }
        }
    }
    else {
        die 'Filters and checks must be either sub{} or []';
    }

    return $result;
}

sub _process {
    my ( $pairs, $param, $key, $check ) = @_;
    my $value = $param->{$key};
    my $iterator = natatime(2, @$pairs);
    while ( my ( $match, $code ) = $iterator->() ) {
        if ( _match($key, $match) ) {
            my $temp = _run_code( $code, $value, $check ? ($param, $key) : undef );
            if ( $check ) {
                return $temp if $temp
            }
            else {
                $value = $temp;
            }
        }
    }
    return if $check;
    return $value;
}

sub _match {
    my ( $a, $b ) = @_;
    if ( !ref($b) ) {
        return $a eq $b;
    }
    elsif ( ref($b) eq 'ARRAY' ) {
        return grep { $a eq $_ } @$b;
    }
    elsif ( ref($b) eq 'Regexp' ) {
        return $a =~ $b;
    }
    else {
        return 0;
    }
}

sub filter {
    my @result = ();
    for (@_) {
        if ( exists $FILTERS{$_} ) {
            push @result, $FILTERS{$_};
        }
        else {
            die "Invalid filter: $_";
        }
    }
    return @result == 1 ? $result[0] : \@result;
}

sub is_required {
    my $err_msg = shift || 'Required';
    return sub {
        return if defined $_[0] && $_[0] ne '';
        return $err_msg;
    };
}

sub is_required_if {
    my ( $condition, $err_msg ) = @_;
    $condition = 0 unless defined $condition;
    $err_msg ||= 'Required';
    if ( ref($condition) && ref($condition) ne 'CODE' ) {
        croak "is_required_if condition must be CODE or SCALAR";
    }
    return sub {
        my ( $value, $params ) = @_;
        my $required =
          ref($condition) eq 'CODE'
          ? $condition->($params)
          : $condition;
        return unless $required;
        return if defined $value && $value ne '';
        return $err_msg;
    };
}

sub is_existing {
    my $err_msg = shift || 'Must be defined';
    return sub {
        return if exists $_[1]->{$_[2]};
        return $err_msg;
    }
}

sub is_equal {
    my ( $other, $err_msg ) = @_;
    $err_msg ||= 'Invalid value';
    return sub {
        return if !defined($_[0]) || $_[0] eq '';
        return if defined $_[1]->{$other} && $_[0] eq $_[1]->{$other};
        return $err_msg;
    };
}

sub is_long_between {
    my ( $min, $max, $err_msg ) = @_;
    $err_msg ||= "Must be between $min and $max symbols";
    return sub {
        return if !defined($_[0]) || $_[0] eq '';
        return if length( $_[0] ) >= $min && length( $_[0] ) <= $max;
        return $err_msg;
    };
}

sub is_long_at_least {
    my ( $length, $err_msg ) = @_;
    $err_msg ||= "Must be at least $length symbols";
    return sub {
        return if !defined($_[0]) || $_[0] eq '';
        return if length( $_[0] ) >= $length;
        return $err_msg;
    };
}

sub is_long_at_most {
    my ( $length, $err_msg ) = @_;
    $err_msg ||= "Must be at the most $length symbols";
    return sub {
        return if !defined($_[0]) || $_[0] eq '';
        return if length( $_[0] ) <= $length;
        return $err_msg;
    };
}

sub is_a {
    my ( $class, $err_msg ) = @_;
    $err_msg ||= "Invalid value";
    return sub {
        return if !defined( $_[0] ) || ref( $_[0] ) eq $class;
        return $err_msg;
    };
}

sub is_like {
    my ( $regexp, $err_msg ) = @_;
    $err_msg ||= "Invalid value";
    croak 'Regexp expected' unless ref($regexp) eq 'Regexp';
    return sub {
        return if !defined($_[0]) || $_[0] eq '';
        return if $_[0] =~ $regexp;
        return $err_msg;
    };
}

sub is_in {
    my ( $arrayref, $err_msg ) = @_;
    $err_msg ||= "Invalid value";
    croak 'ArrayRef expected' unless ref($arrayref) eq 'ARRAY';
    return sub {
        return if !defined($_[0]) || $_[0] eq '';
        return if _match( $_[0], $arrayref );
        return $err_msg;
      }
}

sub new {
    my ( $class, %args ) = @_;
    my $filters = $args{filters};
    if ( defined $filters && ref $filters eq 'HASH' ) {
        for my $key ( keys %$filters ) {
            $FILTERS{$key} = $filters->{$key} if ref $filters->{$key} eq 'CODE';
        }
    }
    bless \%args, $class;
}

sub check {
    my ( $self, $input, $rules, %args ) = @_;
    $self = $self->new( %args ) unless ref $self;

    if ( ref $input ne 'HASH' || ref $rules ne 'HASH' ) {
        confess("Parameters and rules HASH refs are needed");
    }

    $self->{input} = $input;
    $self->{rules} = $rules;
    $self->{result} = validate( $input, $rules );

    return $self;
}

sub AUTOLOAD {
    my $self = shift;
    our $AUTOLOAD;
    my $sub = $AUTOLOAD =~ /::(\w+)$/ ? $1 : undef;
    if ( $sub =~ /(params|rules)/ ) {
        return $self->{$sub};
    }
    elsif ( $sub =~ /(data|error)/ ) {
        if ( my $field = shift ) {
            my $fields = $self->{rules}->{fields};
            if ( scalar(@$fields) ) {
                croak("Undefined field $sub($field)")
                  unless _match( $field, $fields );
            }
            return $self->{result}->{$sub}->{ $field };
        }
        else {
            return {%{$self->{result}->{$sub}}};
        }
    }
    elsif ( $sub eq 'success' ) {
        return $self->{result}->{success}
    }
    elsif ( $sub eq 'to_hash' ) {
        return {%{$self->{result}}}
    }
    else {
        confess "Undefined method $AUTOLOAD";
    }
}

sub DESTROY {}

1;

__END__

=pod

=head1 NAME

Validate::Tiny - Minimalistic data validation

=head1 SYNOPSIS

Filter and validate user input from forms, etc.

    use Validate::Tiny ':all';

    my $rules = {

        # List of fields to look for
        fields => [qw/name email pass pass2 gender/],

        # Filters to run on all fields
        filters => [

            # Remove spaces from all
            qr/.+/ => filter(qw/trim strip/),

            # Lowercase email
            email => filter('lc'),

            # Remove non-alphanumeric symbols from
            # both passwords
            qr/pass?/ => sub {
                $_[0] =~ s/\W/./g;
                $_[0];
            },
        ],

        # Checks to perform on all fields
        checks => [

            # All of these are required
            [qw/name email pass pass2/] => is_required(),

            # pass2 must be equal to pass
            pass2 => is_equal('pass'),

            # custom sub validates an email address
            email => sub {
                my ( $value, $params ) = @_;
                return if Email::Valid->address($value);
                return 'Invalid email';
            },

            # custom sub to validate gender
            gender => sub {
                my ( $value, $params ) = @_;
                return if $value eq 'M' || $value eq 'F';
                return 'Invalid gender';
            }

        ]
    };

    # Validate the input agains the rules
    my $result = validate( $input, $rules );

    if ( $result->{success} ) {
        my $values_hash = $result->{data};
        ...
    }
    else {
        my $errors_hash = $result->{error};
        ...
    }


Or if you prefer an OOP approach:

    use Validate::Tiny;

    my $v = Validate::Tiny->new( %args );
    $v->check( $input, $rules );

    if ( $v->success ) {
        my $values_hash = $v->data;
        my $name        = $v->data('name');
        my $email       = $v->data('email');
        ...;
    }
    else {
        my $errors_hash = $v->error;
        my $name_error  = $v->error('name');
        my $email_error = $v->error('email');
    }

=head1 DESCRIPTION

This module provides a simple, light and minimalistic way of validating
user input. Except perl core modules and some test modules it has no other
dependencies, which is why it does not implement any complicated checks
and filters such as email and credit card matching. The basic idea of this
module is to provide the validation functionality, and leave it up to the
user to write their own data filters and checks. If you need a complete
data validation solution that comes with many ready features, I recommend
you to take a look at L<Data::FormValidator>. If your validation logic is
not too complicated or your form is relatively short, this module is a
decent candidate for your project.

=head1 LOGIC

The basic principle of data/form validation is that any user input must be
sanitized and checked for errors before used in the logic of the program.
Validate::Tiny breaks this process in three steps:

=over

=item 1

Specify the fields you want to work with via L</fields>.  All others will
be disregarded.

=item 2

Filter the fields' values using L</filters>. A filter can be as simple as
changing to lower case or removing excess white space, or very complicated
such as parsing and removing HTML tags.

=item 3

Perform a series of L</checks> on the filtered values, to make sure they
match the requirements. Again, the checks can be very simple as in
checking if the value was defined, or very complicated as in checking if
the value is a valid credit card number.

=back

The validation returns a hash ref which contains C<success> => 1|0,
C<data> and C<error> hashes. If success is 1, C<data> will contain the
filtered values, otherwise C<error> will contain the error messages for
each field.

=head1 EXPORT

This module does not automatically export anything. You can optionally
request any of the below subroutines or use ':all' to export all.

=head1 RULES

Rules provide the specifications for the three step validation
process.  They are represented as a hash, containing references to the
following three arrays: L</fields>, L</filters> and L</checks>.

    my %rules = (
        fields  => \@field_names,
        filters => \@filters_array,
        checks  => \@checks_array
    );

=head2 fields

An array containing the names of the fields that must be filtered, checked
and returned. All others will be disregarded. As of version 0.981 you can
use an empty array for C<fields>, which will work on all input fields.

    my @field_names = qw/username email password password2/;

or

    my @field_names = ();   # Use all input fields

=head2 filters

An array containing name matches and filter subs. The array must have an
even number of elements. Each I<odd> element is a field name match and
each I<even> element is a reference to a filter subroutine or a chain of
filter subroutines. A filter subroutine takes one parameter - the value to
be filtered, and returns the modified value.

    my @filters_array = (
        email => sub { return lc $_[0] },    # Lowercase the email
        password =>
          sub { $_[0] =~ s/\s//g; $_[0] }    # Remove spaces from password
    );

The field name is matched with the perl smart match operator, so you could
have a regular expression or a reference to an array to match several
fields:

    my @filters_array = (
        qr/.+/ => sub { lc $_[0] },    # Lowercase ALL

        [qw/password password2/] => sub {    # Remove spaces from both
            $_[0] =~ s/\s//g;                # password and password2
            $_[0];
        }
    );

Instead of a single filter subroutine, you can pass an array of
subroutines to provide a chain of filters:

    my @filters_array = (
        qr/.+/ => [ sub { lc $_[0] }, sub { ucfirst $_[0] } ]
    );

The above example will first lowercase the value then uppercase its first
letter.

Some simple text filters are provided by the L</filter()> subroutine.

    use Validate::Tiny qw/validate :util/;

    my @filters_array = (
        name => filter(qw/strip trim lc/)
    );

=head3 Adding custom filters

This module exposes C<our %FILTERS>, a hash containing available filters.
To add a filter, add a new key-value to this hash:

    $Validate::Tiny::FILTERS{only_digits} = sub {
        my $val = shift // return;
        $val =~ s/\D//g;
        return $val;
    };

=head3 Filter Support Routines

=head4 filter

    filter( $name1, $name2, ... );

Provides a shortcut to some basic text filters. In reality, it returns a
list of anonymous subs, so the following:

    my $rules = {
        filters => [
            email => filter('lc', 'ucfirst')
        ]
    };

is equivalent to this:

    my $rules = {
        filters => [
            email => [ sub{ lc $_[0] }, sub{ ucfirst $_[0] } ]
        ]
    };

It provides a shortcut for the following filters:

=over

=item trim

Removes leading and trailing white space.

=item strip

Shrinks two or more white spaces to one.

=item lc

Lower case.

=item uc

Upper case.

=item ucfirst

Upper case first letter

=back


=head2 checks

An array ref containing name matches and check subs. The array must have
an even number of elements. Each I<odd> element is a field name match and
each I<even> element is a reference to a check subroutine or a chain of
check subroutines.

A check subroutine takes three parameters - the value to be checked, a
reference to the filtered input hash and a scalar with the name of the
checked field.

B<Example:>

    checks => [
        does_exist => sub {
            my ( $value, $params, $keys ) = @_;
            return "Key doesn't exist in input data"
              unless exists( $params->{$key} );
        }
    ]

A check subroutine must return undef if the check passes or a scalar containing
an error message if the check fails.  The message is not interpreted by
Validate::Tiny, so may take any form, e.g. a string, a reference to
an error object, etc.


B<Example:>

    # Make sure the password is good
    sub is_good_password {
        my ( $value, $params ) = @_;

        if ( !defined $value or $value eq '' ) {
            return;
        }

        if ( length($value) < 6 ) {
            return "The password is too short";
        }

        if ( length($value) > 40 ) {
            return "The password is too long";
        }

        if ( $value eq $params->{username} ) {
            return "Your password can not be the same as your username";
        }

        # At this point we're happy with the password
        return;
    }

    my $rules = {
        fields => [qw/username password/],
        checks => [
            password => \&is_good_password
        ]
    };

It may be a bit counter-intuitive for some people to return undef when the
check passes and an error message when it fails. If you have a huge problem with
this concept, then this module may not be right for you.

B<Important!> Notice that in the beginning of C<is_good_password> we check
if C<$value> is defined and return undef if it is not. This is because it
is not the job of C<is_good_password> to check if C<password> is required.
Its job is to determine if the password is good. Consider the following
example:

    # Password is required and it must pass the check for good password
    #
    my $rules = {
        fields => [qw/username password/],
        checks => [
            password => [ is_required(), \&is_good_password ]
        ]
    };

and this one too:

    # Password is not required, but if it's provided then
    # it must pass the is_good_password constraint.
    #
    my $rules = {
        fields => [qw/username password/],
        checks => [
            username => is_required(),
            password => \&is_good_password
        ]
    };

The above examples show how we make sure that C<password> is defined and
not empty before we check if it is a good password.  Of course we can
check if C<password> is defined inside C<is_good_password>, but it would
be redundant. Also, this approach will fail if C<password> is not
required, but must pass the rules for a good password if provided.

=head3 Chaining

The above example also shows that chaining check subroutines is available
in the same fashion as chaining filter subroutines.  The difference
between chaining filters and chaining checks is that a chain of filters
will always run B<all> filters, and a chain of checks will exit after the
first failed check and return its error message.  This way the
C<$result-E<gt>{error}> hash always has a single error message per field.

=head3 Using closures

When writing reusable check subroutines, sometimes you will want to be
able to pass arguments. Returning closures (anonymous subs) is the
recommended approach:

    sub is_long_between {
        my ( $min, $max ) = @_;
        return sub {
            my $value = shift;
            return if length($value) >= $min && length($value) <= $max;
            return "Must be between $min and $max symbols";
        };
    }

    my $rules = {
        fields => qw/password/,
        checks => [
            password => is_long_between( 6, 40 )
        ]
    };

=head3 Check Support Routines

Validate::Tiny provides a number of predicates to simplify writing
rules.  They may be passed an optional error message.  Like those
returned by custom check routines, the message is not interpreted by
Validate::Tiny, so may take any form, e.g. a string, a reference to an
error object, etc.

=head4 is_required

    is_required( $optional_error_message );

C<is_required> provides a shortcut to an anonymous subroutine that
checks if the matched field is defined and it is not an empty
string.
Optionally, you can provide a custom error message. The default is the string,  I<Required>.


=head4 is_required_if

    is_required_if( $condition, $optional_error_message );

Require a field conditionally. The condition can be either a scalar or a
code reference that returns true/false value. If the condition is a code
reference, it will be passed the C<$params> hash with all filtered fields.
Optionally, you can provide a custom error message. The default is the string,  I<Required>.

Example:

    my $rules = {
        fields => [qw/country state/],
        checks => [
            country => is_required(),
            state   => is_required_if(
                sub {
                    my $params = shift;
                    return $params->{country} eq 'USA';
                },
                "Must select a state if you're in the USA"
            )
        ]
    };

Second example:

    our $month = 'October';
    my $rules = {
        fields => ['mustache'],
        checks => [
            mustache => is_required_if(
                $month eq 'October',
                "You must grow a mustache this month!"
            )
        ]
    };

=head4 is_existing

    is_existing( $optional_error_message );

Much like C<is_required>, but checks if the field contains any value, even an
empty string and C<undef>.
Optionally, you can provide a custom error message. The default is the string,  I<Must be defined>.

=head4 is_equal

    is_equal( $other_field_name, $optional_error_message );

C<is_equal> checks if the value of the matched field is the same as the
value of another field within the input hash.
Optionally, you can provide a custom error message. The default is the string,  I<Invalid value>.

Example:

    my $rules = {
        checks => [
            password2 => is_equal("password", "Passwords don't match")
        ]
    };

=head4 is_long_between

    is_long_between( $min, $max, $optional_error_message );

Checks if the length of the value is >= C<$min> and <= C<$max>. Optionally
you can provide a custom error message. The default is the string,  I<Invalid value>.

Example:

    my $rules = {
        checks => [
            username => is_long_between( 6, 25, 'Bad username' )
        ]
    };


=head4 is_long_at_least

    is_long_at_least( $length, $optional_error_message );

Checks if the length of the value is >= C<$length>. Optionally you can
provide a custom error message. The default is the string,  I<Must be at least %i
symbols>.

Example:

    my $rules = {
        checks => [
            zip_code => is_long_at_least( 5, 'Bad zip code' )
        ]
    };


=head4 is_long_at_most

    is_long_at_most( $length, $optional_error_message );

Checks if the length of the value is <= C<$length>. Optionally you can
provide a custom error message. The default is the string,  I<Must be at the most %i
symbols>.

Example:

    my $rules = {
        checks => [
            city_name => is_long_at_most( 40, 'City name is too long' )
        ]
    };


=head4 is_a

    is_a ( $class, $optional_error_message );

Checks if the value is an instance of a class. This can be particularly
useful, when you need to parse dates or other user input that needs to get
converted to an object. Since the filters get executed before checks, you
can use them to instantiate the data, then use C<is_a> to check if you got
a successful object.
Optionally you can provide a custom error message. The default is the string,  I<Invalid value>.

Example:

    use DateTime::Format::Natural;
    use Try::Tiny;

    my $parser = DateTime::Format::Natural->new;

    my $rules = {
        fields  => ['date'],

        filters => [
            date => sub {
                try {
                    $parser->parse_datetime( $_[0] );
                }
                catch {
                    $_[0]
                }
            }
        ],

        checks => [
            date => is_a("DateTime", "Ivalid date")
        ]
    };


=head4 is_like

    is_like ( $regexp, $optional_error_message );

Checks if the value matches a regular expression.
Optionally you can provide a custom error message. The default is the string,  I<Invalid value>.

Example:


    my $rules = {
        checks => [
            username => is_like( qr/^[a-z0-9_]{6,20}$/, "Bad username" )
        ]
    };

=head4 is_in

    is_in ( $arrayref, $optional_error_message );

Checks if the value matches a set of values.
Optionally you can provide a custom error message. The default is the string,  I<Invalid value>.

    Example:

    my @cities = qw/Alchevsk Kiev Odessa/;
    my $rules = {
        checks => [
            city => is_in( \@cities, "We only deliver to " . join(',', @cities))
        ]
    };



=head1 PROCEDURAL INTERFACE

=head2 validate

    use Validate::Tiny qw/validate/;

    my $result = validate( \%input, \%rules );

Validates user input against a set of rules. The input is expected to be a
reference to a hash.

=head3 Return value

C<validate> returns a hash ref with three elements:

    my $result = validate(\%input, \%rules);

    # Now $result looks like this
    $result = {
        success => 1,       # or 0 if checks didn't pass
        data    => \%data,
        error   => \%error
    };

If C<success> is 1 all of the filtered input will be in C<%data>,
otherwise the error messages will be stored in C<%error>. If C<success> is
0, C<%data> may or may not contain values, but its use is not recommended.


=head1 OBJECT INTERFACE

=head2 new( %args )

At this point the only argument you can use in C<%args> is C<filters>,
which should be a hashref with additional filters to be added to the
C<%FILTERS> hash.

    my $v = Validate::Tiny->new(
        filters => {
            only_digits => sub {
                my $val = shift // return;
                $val =~ s/\D//g;
                return $val;
            }
        }
    );

=head2 check( \%input, %rules )

Checks the input agains the rules and initalized internal result state.

    my %input = ( bar => 'abc' );
    my %rules = ( fields => ['bar'], filters => filter('uc') );
    $v->check( \%input, \%rules );

    if ( $v->success ) {
        ...;
    }

=head2 success

Returns a true value if the input passed all the rules.

=head2 data

Returns a hash reference to all filtered fields. If called with a
parameter, it will return the value of that field or croak if there is no
such field defined in the fields array.

    my $all_fields = $result->data;
    my $email      = $result->data('email');

=head2 error

Returns a hash reference to all error messages. If called with a
parameter, it will return the error message of that field, or croak if
there is no such field.

    my $errors = $result->error;
    my $email = $result->error('email');

=head2 to_hash

Return a result hash, much like using the procedural interface. See the
output of L</validate> for more information.

=head1 I18N

A check function is considered failing if it returns a value. In the above
examples we showed you how to return error strings. If you want to
internationalize your errors, you can make your check closures return
L<Locale::Maketext> functions, or any other i18n values.

=head1 SEE ALSO

L<Data::FormValidator>

=head1 BUGS

Bug reports and patches are welcome. Reports which include a failing
Test::More style test are helpful and will receive priority.

You may also fork the module on Github:
https://github.com/naturalist/Validate--Tiny

=head1 AUTHOR

    Stefan G. (cpan: MINIMAL) - minimal@cpan.org

=head1 CONTRIBUTORS

    Viktor Turskyi (cpan: KOORCHIK) - koorchik@cpan.org
    Ivan Simonik (cpan: SIMONIKI) - simoniki@cpan.org
    Daya Sagar Nune (cpan: DAYANUNE) - daya.webtech@gmail.com
    val - valkoles@gmail.com
    Patrice Clement (cpan: MONSIEURP) - monsieurp@gentoo.org
    Graham Ollis (cpan: PLICEASE)
    Diab Jerius (cpan DJERIUS)

=head1 LICENCE

This program is free software; you can redistribute it and/or modify it
under the terms as perl itself.

=cut

t/00-load.t  view on Meta::CPAN

#!/usr/bin/perl

use Test::More tests => 1;

BEGIN {
    use_ok( 'Validate::Tiny' ) || print "Bail out!\n";
}

diag( "Testing Validate::Tiny $Validate::Tiny::VERSION, Perl $], $^X" );

t/01-filters.t  view on Meta::CPAN

#!/usr/bin/perl

use strict;
use warnings;

use Test::More tests => 12;
use Validate::Tiny ':all';

my $ok;

my $i = { a => 'a', b => 'b' };
my $r = { fields => ['a', 'b'] };

my $filter = sub { ord($_[0]) };

# First
$r->{filters} = [ a => filter('uc') ];
is_deeply validate( $i, $r )->{data},  { a => 'A', b => 'b' };

# Array
$r->{filters} = [ [qw/a b/] => filter('uc') ];
is_deeply validate( $i, $r )->{data},  { a => 'A', b => 'B' };

# Regex 1
$r->{filters} = [ qr/.+/ => filter('uc') ];
is_deeply validate( $i, $r )->{data},  { a => 'A', b => 'B' };

# Regex 2
$r->{filters} = [ qr/b/ => filter('uc') ];
is_deeply validate( $i, $r )->{data},  { a => 'a', b => 'B' };

# Missing field
$r->{filters} = [ a => filter('uc') ];
is_deeply validate( { b => 'b' }, $r )->{data},  { b => 'b' };

# Double filter
$r->{filters} = [ a => [filter('uc'), $filter] ];
is_deeply validate( $i, $r )->{data},  { a => ord('A'), b => 'b' };

$r->{filters} = [ a => [filter('uc'), filter('lc')] ];
is_deeply validate( $i, $r )->{data},  { a => 'a', b => 'b' };

$r->{filters} = [ a => [filter(qw/uc lc/)] ];
is_deeply validate( $i, $r )->{data},  { a => 'a', b => 'b' };

$r->{filters} = [ [qw/a b/] => [filter('uc'), $filter] ];
is_deeply validate( $i, $r )->{data},  { a => ord('A'), b => ord('B') };
is_deeply validate( {}, $r )->{data},  {};

# Deep
$r->{filters} = [ a => [[ filter('uc') ], $filter] ];
is_deeply validate( $i, $r )->{data},  { a => ord('A'), b => 'b' };

# Same field
$r->{filters} = [ a => filter('uc'), a => $filter ];
is_deeply validate( $i, $r )->{data},  { a => ord('A'), b => 'b' };


t/02-checks.t  view on Meta::CPAN

#!/usr/bin/perl

use strict;
use warnings;

use Test::More tests => 23;
use Validate::Tiny ':all';

my $r = { fields => [qw/a b/] };
my ( $i, $o );
my @checks;
my $c = sub {
    return unless defined $_[0] && $_[0] ne '';
    return $_[0] =~ /^\w+$/ ? undef : 'message';
};

# Single
$r->{checks} = [ a => is_required() ];
$i = { a => 'a', b => 'b' };
$o = { success => 1, data => $i, error => {} };
is_deeply validate( $i, $r ), $o;

$i = { a => '', b => 'b' };
$o = { success => 0, data => $i, error => { a => 'Required' } };
is_deeply validate( $i, $r ), $o;

$i = { a => 0, b => 'b' };
$o = { success => 1, data => $i, error => {} };
is_deeply validate( $i, $r ), $o;

$i = { b => 'b' };
$o = { success => 0, data => $i, error => { a => 'Required' } };
is_deeply validate( $i, $r ), $o;

# Combine fields in the left side
@checks = (
    [ [qw/a b/] => is_required() ],
    [ qr/.+/ => is_required() ]
);

for ( @checks ) {
    $r->{checks} = $_;
    $i = { a => '', b => 'b' };
    $o = { success => 0, data => $i, error => { a => 'Required' } };
    is_deeply validate( $i, $r ), $o;

    $i = { a => 'a', b => '' };
    $o = { success => 0, data => $i, error => { b => 'Required' } };
    is_deeply validate( $i, $r ), $o;

    $i = { b => '' };
    $o = { success => 0, data => $i, error => { a => 'Required', b => 'Required' } };
    is_deeply validate( $i, $r ), $o;
}


# Chaining
@checks = (
    [ a => is_required(),   a => $c ],
    [ a => [ is_required(), $c ] ],
    [ a => [ [ is_required() ], [$c] ] ]
);

for (@checks) {
    $r->{checks} = $_;

    $i = { a => 'a' };
    $o = { success => 1, data => $i, error => {} };
    is_deeply validate( $i, $r ), $o;

    $i = { a => '' };
    $o = { success => 0, data => $i, error => { a => 'Required' } };
    is_deeply validate( $i, $r ), $o;

    $i = { a => '%' };
    $o = { success => 0, data => $i, error => { a => 'message' } };
    is_deeply validate( $i, $r ), $o;
}

# Non-required
$r->{checks} = [ a => $c ];
$i = { a => 'w' };
$o = { success => 1, data => $i, error => {} };
is_deeply validate($i, $r), $o;

$i = { a => '%' };
$o = { success => 0, data => $i, error => { a => 'message' } };
is_deeply validate($i, $r), $o;

$i = { a => '' };
$o = { success => 1, data => $i, error => {} };
is_deeply validate($i, $r), $o;

$i = { b => 'b' };
$o = { success => 1, data => $i, error => {} };
is_deeply validate($i, $r), $o;

t/021-undef.t  view on Meta::CPAN

use strict;
use warnings;

use Test::More tests => 3;
use Validate::Tiny ':all';

my $r = {
    fields => ['a'],
    checks => [
        a => is_required
    ]
};

my ($i, $o);

$i = { a => undef };
$o = validate( $i, $r );
ok !$o->{success};

$r->{filters} = [
    a => sub { defined $_[0] ? $_[0] : 'mucus' }
];

$o = validate( $i, $r );
ok $o->{success};
is $o->{data}->{a}, 'mucus';

t/022-key.t  view on Meta::CPAN

use strict;
use warnings;

use Test::More tests => 2;
use Validate::Tiny ':all';

my $r = {
    fields => ['a'],
    checks => [
        a => [
            sub {
                my ( $val, $param, $key ) = @_;
                $param->{$key} == $val ? undef : 'Err';
            }
        ]
    ]
};

my ($i, $o);

$i = { a => 4 };
$o = validate( $i, $r );
ok $o->{success};
is $o->{data}->{a}, 4;

t/03-arrays.t  view on Meta::CPAN


use strict;
use warnings;

use Test::More tests => 2;
use Validate::Tiny ':all';

my $f = sub {
    [ grep { $_ > 2 } @{ $_[0] } ];
};

my $c = sub {
    for ( @{ $_[0] } ) { return 'Error' if $_ > 5 }
    undef;
};

my $r = { fields => ['a'], filters => [ a => $f ], checks => [ a => $c ] };
my $i = { a => [ 1, 2, 3, 4 ] };
my $o = { success => 1, data => { a => [ 3, 4 ] }, error => {} };
is_deeply validate( $i, $r ), $o;

$i = { a => [ 1, 2, 3, 4, 20, 30 ] };
$o = { success => 0, data => { a => [ 3, 4, 20, 30 ] }, error => { a => 'Error' } };
is_deeply validate( $i, $r ), $o;

t/04-oop.t  view on Meta::CPAN

#!/usr/bin/perl

use strict;
use warnings;

use Test::More;
use Validate::Tiny;

my $rules = {
    fields => [qw/a b/],
    checks => [ a => sub { $_[0] < 5 ? undef : 'Error' } ]
};
my $result = Validate::Tiny->check( { a=> 1 }, $rules );
my $r2 = Validate::Tiny::validate( { a => 1 }, $rules );

# Sanity
{
    local $@;
    eval { $result->something };
    ok $@, "wrong accessor";

    eval { $result->data('something') };
    ok $@, "wrong data field";

    eval { $result->error('something') };
    ok $@, "wrong error field";
}

# Empty fields list
{
    my $rules = { fields => [] };
    my $result = Validate::Tiny->check( { a => 1 }, $rules );
    is $result->data('a'), 1;
    is $result->data('b'), undef;
}

ok( $result->success, 'success' );
is( $result->data('a'), 1, 'functional access data' );
is( $result->data->{a}, 1, 'hash access data' );
is( $result->data('b'), undef, 'return undef if field has no value 1' );
is( $result->data->{b}, undef, 'return undef if field has no value 2' );
eval { $result->data('c') };
ok($@, 'croaks if the field has not been defined');
is( $result->data->{c}, undef, 'returns undef on undefined field via hash' );

is_deeply( $result->data,    $r2->{data}, 'data match' );
$result->data->{a} = 'foo';
is_deeply( $result->data,    $r2->{data}, 'can not change data' );

is_deeply( $result->error,   $r2->{error}, 'error match' );
$result->error->{a} = 'foo';
is_deeply( $result->error,   $r2->{error}, 'can not change error' );

is_deeply( $result->success, $r2->{success}, 'success match' );
is_deeply( $result->to_hash, $r2, 'to_hash match' );

$result = Validate::Tiny->check( { a => 11 }, $rules );
$r2 = Validate::Tiny::validate( { a => 11 }, $rules );
is( $result->error('a'), 'Error', 'functional error' );
is( $result->error->{a}, 'Error', 'hash error' );
is_deeply( $result->data,    $r2->{data} );
is_deeply( $result->error,   $r2->{error} );
is_deeply( $result->success, $r2->{success} );
is_deeply( $result->to_hash, $r2 );

$rules->{checks} = [
    a => sub { $_[0] < 5 ? undef : 'ErrorA' },
    b => sub { $_[0] < 2 ? undef : 'ErrorB' }
];

# New and filters
{
    my $v = Validate::Tiny->new(
        filters => {
            only_digits => sub {
                my $val = shift;
                return unless defined $val;
                $val =~ s/\D//g;
                return $val;
            }
        }
    );

    my $rules = {
        fields  => ['a'],
        filters => [ a => Validate::Tiny::filter( 'trim', 'only_digits' ) ]
    };
    $v->check( { a => ' abc123 ' }, $rules );

    is $v->data->{a}, '123';
}

done_testing;

t/05-sanity.t  view on Meta::CPAN

#!/usr/bin/perl

use strict;
use warnings;

use Test::More tests => 12;
use Validate::Tiny ':all';

eval { validate( {}, {} ) };
ok $@, "Fields must be defined";

eval { validate( {}, { fields => {} } ) };
ok $@, "Fields must be an array";

eval { validate( {}, { fields => [qw/a/], filters => [ 1, 2, 3 ] } ) };
ok $@, "Fields must have even number of elements";

{
    my $res = validate( { a => 1, b => 2 }, { fields => [] } );
    is_deeply $res, { success => 1, data => { a => 1, b => 2 }, error => {} },
      "Empty fields takes all";
}

eval { validate( {}, { fields => [qw/a/], checks => [ 1, 2, 3 ] } ) };
ok $@, "Checks must have even number of elements";

eval { validate( {}, { fields => [qw/a/], filters => { a => 1 } } ) };
ok $@, "Filters must be an arrayref";

eval { validate( {}, { fields => [qw/a/], checks => { a => 1 } } ) };
ok $@, "Checks must be an arrayref";

eval { validate( {}, { fields => [qw/a/], checks => [ a => 1 ] } ) };
ok $@, "Each check must be code or arrayref";

eval { validate( { a => 2 }, { fields => [qw/a/], filters => [ a => 1 ] } ) };
ok $@, "Each filter must be code or arrayref";

eval { validate( {}, { fields => ['a'], something => [ 1, 2, 3 ] } ) };
ok $@, "Checks for misspelled keys";

eval { my $result = Validate::Tiny->check(1,2) };
ok $@, "Wrong params to constructor";

eval { my $result = Validate::Tiny->check({}) };
ok $@, "Wrong params to constructor 2";


t/author-pod-syntax.t  view on Meta::CPAN

#!perl

BEGIN {
  unless ($ENV{AUTHOR_TESTING}) {
    print qq{1..0 # SKIP these tests are for testing by the author\n};
    exit
  }
}

# This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests.
use strict; use warnings;
use Test::More;
use Test::Pod 1.41;

all_pod_files_ok();

t/checks/01-is_required.t  view on Meta::CPAN

use strict;
use warnings;
use Test::More tests => 9;
use Validate::Tiny ':all';

my $rules = {
    fields => [qw/a b c/],
    checks => [
        a => is_required(),
        b => is_required('NO'),
    ]
};

my $r;

$r = validate( {}, $rules );
ok !$r->{success};
is_deeply $r->{error}, { a => 'Required', b => 'NO' };

$r = validate( {a => 'z', b => '', c => 'y' }, $rules );
ok !$r->{success};
is_deeply $r->{error}, { b => 'NO' };

$r = validate( {a => '', b => 'z' }, $rules );
ok !$r->{success};
is_deeply $r->{error}, { a => 'Required' };

$r = validate( {a => 'x', b => 'z' }, $rules );
ok $r->{success};
is_deeply $r->{data}, { a => 'x', b => 'z' };
is_deeply $r->{error}, {};

t/checks/02-is_required_if.t  view on Meta::CPAN

use strict;
use warnings;
use Test::More tests => 10;
use Validate::Tiny ':all';

my $rules = {
    fields => [qw/a b/],
};

my $r;

$rules->{checks} = [ a => is_required_if(1) ];
$r = validate( { a => '' }, $rules );
ok !$r->{success};
ok $r->{error}->{a};
$r = validate( { a => 'z' }, $rules );
ok $r->{success};

$rules->{checks} = [ a => is_required_if(0) ];
$r = validate( { a => '' }, $rules );
ok $r->{success};
$r = validate( { a => 'j' }, $rules );
ok $r->{success};

my $cond = sub {
    my $p = shift;
    return defined $p->{b} && $p->{b} eq 'z';
};

$rules->{checks} = [ a => is_required_if( $cond, 'foo' ) ];
$r = validate( { a => '' }, $rules );
ok $r->{success};
$r = validate( { a => '', b => 'z' }, $rules );
ok !$r->{success};
is $r->{error}->{a}, 'foo';
$r = validate( { a => 'k', b => 'z' }, $rules );
ok $r->{success};

{
    local $@;
    eval { is_required_id([]) };
    ok $@;
}

t/checks/03-is_equal.t  view on Meta::CPAN


use strict;
use warnings;
use Test::More tests => 6;
use Validate::Tiny ':all';

my $r = { fields => [qw/a b/] };

$r->{checks} = [ a => is_equal('b') ];
ok validate({a => '', b => 1}, $r)->{success};
ok !validate({a => '0', b => ''}, $r)->{success};
ok validate({a => '1', b => '1'}, $r)->{success};

$r->{checks} = [ a => [is_required(), is_equal('b')] ];
ok !validate({a => '', b => ''}, $r)->{success};
ok !validate({a => '', b => '1'}, $r)->{success};

$r->{checks} = [ a => [is_equal('b', 'NO')] ];
my $e = validate( {a => '1', b => '2'}, $r );
is $e->{error}->{a}, 'NO';

t/checks/04-is_long.t  view on Meta::CPAN

use strict;
use warnings;
use Test::More;
use Validate::Tiny ':all';

my $r = { fields => [qw/a b/] };

# is_long_between
{
    $r->{checks} = [ a => is_long_between( 2, 3 ) ];
    ok validate( { a => '' }, $r )->{success};
    ok !validate( { a => 'a' }, $r )->{success};
    ok validate( { a => 'ab' },  $r )->{success};
    ok validate( { a => 'abc' }, $r )->{success};
    ok !validate( { a => 'abcd' }, $r )->{success};

    $r->{checks} = [ a => is_long_between( 2, 3, 'NO' ) ];
    is validate( { a => 'abcd' }, $r )->{error}->{a}, "NO";
}

# is_long_at_least
{
    $r->{checks} = [ a => is_long_at_least(2) ];
    ok validate({a => ''}, $r)->{success};
    ok !validate({a => 'a'}, $r)->{success};
    ok validate({a => 'ab'}, $r)->{success};

    $r->{checks} = [ a => is_long_at_least(2, 'NO') ];
    is validate( { a => 'a' }, $r )->{error}->{a}, "NO";
}

# is_long_at_most (irrelevant)
{
    $r->{checks} = [ a => is_long_at_most(2) ];
    ok validate({a => ''}, $r)->{success};
    ok !validate({a => 'abc'}, $r)->{success};
    ok validate({a => 'ab'}, $r)->{success};
    ok validate({a => 'a'}, $r)->{success};

    $r->{checks} = [ a => is_long_at_most(2, 'NO') ];
    is validate( { a => 'abcd' }, $r )->{error}->{a}, "NO";
}

done_testing;

t/checks/05-is_a.t  view on Meta::CPAN


package Class;
sub new { bless [] }

package main;
use strict;
use warnings;
use Test::More tests => 5;
use Validate::Tiny ':all';

my $r = { fields => [qw/a b/] };

$r->{checks} = [ a => is_a('Class') ];
ok validate( { a => undef }, $r )->{success};
ok !validate( { a => '0' }, $r )->{success};
ok validate( { a => '0' }, $r )->{error}->{a};
ok validate( { a => Class->new }, $r )->{success};

$r->{checks} = [ a => is_a('Class', 'NO') ];
is validate( { a => '0' }, $r )->{error}->{a}, 'NO';

t/checks/06-is_like.t  view on Meta::CPAN

use strict;
use warnings;
use Test::More tests => 6;
use Validate::Tiny ':all';

my $r = { fields => [qw/a b/] };

$r->{checks} = [ a => is_like(qr/^[a-z]$/) ];
ok validate({a => ''}, $r)->{success};
ok !validate({a => '0'}, $r)->{success};
ok validate({a => '0'}, $r)->{error}->{a};
ok validate({a => 'a'}, $r)->{success};

$r->{checks} = [ a => is_like(qr/^[a-z]$/,'NO') ];
is validate({a => '0'}, $r)->{error}->{a}, 'NO';

eval { is_like('non-regex') };
ok $@;

t/checks/07-is_in.t  view on Meta::CPAN

use strict;
use warnings;
use Test::More tests => 6;
use Validate::Tiny ':all';

my $r = { fields => [qw/a b/] };

$r->{checks} = [ a => is_in([1,2,3]) ];
ok validate({a => ''}, $r)->{success};
ok !validate({a => '0'}, $r)->{success};
ok validate({a => '0'}, $r)->{error}->{a};
ok validate({a => '3'}, $r)->{success};

$r->{checks} = [ a => is_in([1,2,3], 'NO') ];
is validate({a => '0'}, $r)->{error}->{a}, 'NO';

{
    local $@;
    eval { is_in('boobs') };
    ok $@;
}

t/checks/09-is_existing.t  view on Meta::CPAN

use strict;
use warnings;

use Test::More;
use Validate::Tiny ':all';

my $rules = {
    fields => [qw/a b/],
    checks => [
        a => is_existing(),
        b => is_existing('NO')
    ]
};

my $r;

$r = validate({}, $rules);
ok !$r->{success};
is_deeply $r->{error}, { a => 'Must be defined', b => 'NO' };

$r = validate( {a => 'z', b => ''}, $rules );
ok $r->{success};

$r = validate( {a => '', b => ''}, $rules );
ok $r->{success};

done_testing;

t/filters/01-trim.t  view on Meta::CPAN


use strict;
use warnings;

use Validate::Tiny ':all';
use Test::More;

my $rules = {
    fields  => ['a'],
    filters => [ a => filter('trim') ]
};

my $res = validate({a => undef}, $rules);
is $res->{a}, undef;

for my $e (" ", "\n", "\r") {
    for ("${e}a${e}", "${e}a", "a${e}", "${e}${e}a${e}${e}") {
        my $res = validate({ a => $_ }, $rules);
        is $res->{data}->{a}, 'a', "OK for [$_]";
    }
}

done_testing;

t/filters/02-strip.t  view on Meta::CPAN

use strict;
use warnings;

use Validate::Tiny ':all';
use Test::More;

my $rules = {
    fields  => ['a'],
    filters => [ a => filter('strip') ]
};

my $res = validate({a => undef}, $rules);
is $res->{a}, undef;

for ('a b', 'a  b', 'a   b') {
    my $res = validate({ a => $_ }, $rules);
    is $res->{data}->{a}, 'a b', "OK for $_ [space]";
}

for ("a\nb", "a\n\nb", "a\n\n\nb") {
    my $res = validate({ a => $_ }, $rules);
    is $res->{data}->{a}, "a\nb", "OK for $_ [new line]";
}

for ("a\rb", "a\r\rb", "a\r\r\rb") {
    my $res = validate({ a => $_ }, $rules);
    is $res->{data}->{a}, "a\rb", "OK for $_ [line feed]";
}

done_testing;

t/filters/03-case.t  view on Meta::CPAN


use strict;
use warnings;

use Validate::Tiny ':all';
use Test::More;

my $rules = {
    fields  => [qw/a b c/],
    filters => [ a => filter('lc'), b => filter('uc'), c => filter('ucfirst') ]
};

my $input = {
    a => 'BAR',
    b => 'foo',
    c => 'baz'
};

my $res = validate({a => undef}, $rules);
is $res->{a}, undef;

$res = validate($input, $rules);
is $res->{data}->{a}, 'bar', "lc";
is $res->{data}->{b}, 'FOO', "uc";
is $res->{data}->{c}, 'Baz', "ucfirst";

done_testing;

t/filters/04-custom.t  view on Meta::CPAN


use strict;
use warnings;

use Validate::Tiny ':all';
use Test::More;

$Validate::Tiny::FILTERS{only_digits} = sub {
    my $val = shift;
    return unless defined $val;
    $val =~ s/\D//g;
    return $val;
};

my $rules = {
    fields  => ['a'],
    filters => [ a => filter('trim', 'only_digits') ]
};

my $res = validate({a => undef}, $rules);
is $res->{a}, undef;

$res = validate({ a => " abc123 " }, $rules);
is $res->{data}->{a}, '123';


done_testing;

t/subs/01-match.t  view on Meta::CPAN

use strict;
use warnings;

use Test::More tests => 7;
use Validate::Tiny;

# Scalar
ok Validate::Tiny::_match( 'foo', 'foo' );
ok !Validate::Tiny::_match( 'foo', 'goo' );

# Array
ok Validate::Tiny::_match( 'foo', [qw/bar foo baz/] );
ok !Validate::Tiny::_match( 'foo', [qw/bar goo baz/] );

# Regexp
ok Validate::Tiny::_match( 'FOO', qr/foo/i );
ok !Validate::Tiny::_match( 'foo', qr/bar/ );

# Other
ok !Validate::Tiny::_match( 'foo', { foo => 1 } );



( run in 1.028 second using v1.01-cache-2.11-cpan-e9daa2b36ef )