<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package Validator::Custom;
use Object::Simple -base;
use 5.008001;
our $VERSION = '0.22';

use Carp 'croak';
use Validator::Custom::Constraint;
use Validator::Custom::Result;
use Validator::Custom::Rule;

has ['data_filter', 'rule', 'rule_obj'];
has error_stock =&gt; 1;

has syntax =&gt; &lt;&lt;'EOS';
### Syntax of validation rule
my $rule = [                            # 1 Rule: Array reference
  key =&gt; [                              # 2 Constraints: Array reference
      'constraint',                     # 3 Constraint: String
      {'constraint' =&gt; $args}           #   or Hash reference (with Arguments)
      ['constraint' =&gt; 'Error Message'],#   or Array reference (with Message)
  ],
  key =&gt; [                              # 4 With Arguments and Message
      [{constraint =&gt; $args}, 'Error Message']
                                        
  ],
  {key =&gt; ['key1', 'key2']} =&gt; [        # 5.1 Multi-parameters validation
      'constraint'
  ],
  {key =&gt; qr/^key/} =&gt; [                # 5.2 Multi-parameters validation
      'constraint'                              using regular expression
  ],
  key =&gt; [
      '@constraint'                     # 6 Multi-values validation
  ],
  key =&gt; {message =&gt; 'err', ... } =&gt; [  # 7 with Options
      'constraint'
  ],
  key =&gt; [
      '!constraint'                     # 8 Negativate constraint
  ],
  key =&gt; [
      'constraint1 || constraint2'      # 9 "OR" Condition
  ],
];

EOS

sub js_fill_form_button {
  my ($self, $rule) = @_;
  
  my $r = $self-&gt;_parse_random_string_rule($rule);
  
  require JSON;
  my $r_json = JSON-&gt;new-&gt;encode($r);
  
  my $javascript = &lt;&lt; "EOS";
(function () {

  var rule = $r_json;

  var create_random_value = function (rule, name) {
    var patterns = rule[name];
    if (patterns === undefined) {
      return "";
    }
    
    var value = "";
    for (var i = 0; i &lt; patterns.length; i++) {
      var pattern = patterns[i];
      var num = Math.floor(Math.random() * pattern.length);
      value = value + pattern[num];
    }
    
    return value;
  };
  
  var addEvent = (function(){
    if(document.addEventListener) {
      return function(node,type,handler){
        node.addEventListener(type,handler,false);
      };
    } else if (document.attachEvent) {
      return function(node,type,handler){
        node.attachEvent('on' + type, function(evt){
          handler.call(node, evt);
        });
      };
    }
  })();
  
  var button = document.createElement("input");
  button.setAttribute("type","button");
  button.value = "Fill Form";
  document.body.insertBefore(button, document.body.firstChild)

  addEvent(
    button,
    "click",
    function () {
      
      var input_elems = document.getElementsByTagName('input');
      var radio_names = {};
      var checkbox_names = {};
      for (var i = 0; i &lt; input_elems.length; i++) {
        var e = input_elems[i];

        var name = e.getAttribute("name");
        var type = e.getAttribute("type");
        if (type === "text" || type === "hidden" || type === "password") {
          var value = create_random_value(rule, name);
          e.value = value;
        }
        else if (type === "checkbox") {
          e.checked = Math.floor(Math.random() * 2) ? true : false;
        }
        else if (type === "radio") {
          radio_names[name] = 1;
        }
      }
      
      for (name in radio_names) {
        var elems = document.getElementsByName(name);
        var num = Math.floor(Math.random() * elems.length);
        elems[num].checked = true;
      }
      
      var textarea_elems = document.getElementsByTagName("textarea");
      for (var i = 0; i &lt; textarea_elems.length; i++) {
        var e = textarea_elems[i];
        
        var name = e.getAttribute("name");
        var value = create_random_value(rule, name);
        
        var text = document.createTextNode(value);
        
        if (e.firstChild) {
          e.removeChild(e.firstChild);
        }
        
        e.appendChild(text);
      }
      
      var select_elems = document.getElementsByTagName("select");
      for (var i = 0; i &lt; select_elems.length; i++) {
        var e = select_elems[i];
        var options = e.options;
        if (e.multiple) {
          for (var k = 0; k &lt; options.length; k++) {
            options[k].selected = Math.floor(Math.random() * 2) ? true : false;
          }
        }
        else {
          var num = Math.floor(Math.random() * options.length);
          e.selectedIndex = num;
        }
      }
    }
  );
})();
EOS

  return $javascript;
}

sub new {
  my $self = shift-&gt;SUPER::new(@_);

  $self-&gt;register_constraint(
    any               =&gt; sub { 1 },
    ascii             =&gt; \&amp;Validator::Custom::Constraint::ascii,
    between           =&gt; \&amp;Validator::Custom::Constraint::between,
    blank             =&gt; \&amp;Validator::Custom::Constraint::blank,
    date_to_timepiece =&gt; \&amp;Validator::Custom::Constraint::date_to_timepiece,
    datetime_to_timepiece =&gt; \&amp;Validator::Custom::Constraint::datetime_to_timepiece,
    decimal           =&gt; \&amp;Validator::Custom::Constraint::decimal,
    defined           =&gt; sub { defined $_[0] },
    duplication       =&gt; \&amp;Validator::Custom::Constraint::duplication,
    equal_to          =&gt; \&amp;Validator::Custom::Constraint::equal_to,
    greater_than      =&gt; \&amp;Validator::Custom::Constraint::greater_than,
    http_url          =&gt; \&amp;Validator::Custom::Constraint::http_url,
    int               =&gt; \&amp;Validator::Custom::Constraint::int,
    in_array          =&gt; \&amp;Validator::Custom::Constraint::in_array,
    length            =&gt; \&amp;Validator::Custom::Constraint::length,
    less_than         =&gt; \&amp;Validator::Custom::Constraint::less_than,
    merge             =&gt; \&amp;Validator::Custom::Constraint::merge,
    not_defined       =&gt; \&amp;Validator::Custom::Constraint::not_defined,
    not_space         =&gt; \&amp;Validator::Custom::Constraint::not_space,
    not_blank         =&gt; \&amp;Validator::Custom::Constraint::not_blank,
    uint              =&gt; \&amp;Validator::Custom::Constraint::uint,
    regex             =&gt; \&amp;Validator::Custom::Constraint::regex,
    selected_at_least =&gt; \&amp;Validator::Custom::Constraint::selected_at_least,
    shift             =&gt; \&amp;Validator::Custom::Constraint::shift_array,
    space             =&gt; \&amp;Validator::Custom::Constraint::space,
    to_array          =&gt; \&amp;Validator::Custom::Constraint::to_array,
    trim              =&gt; \&amp;Validator::Custom::Constraint::trim,
    trim_collapse     =&gt; \&amp;Validator::Custom::Constraint::trim_collapse,
    trim_lead         =&gt; \&amp;Validator::Custom::Constraint::trim_lead,
    trim_trail        =&gt; \&amp;Validator::Custom::Constraint::trim_trail,
    trim_uni          =&gt; \&amp;Validator::Custom::Constraint::trim_uni,
    trim_uni_collapse =&gt; \&amp;Validator::Custom::Constraint::trim_uni_collapse,
    trim_uni_lead     =&gt; \&amp;Validator::Custom::Constraint::trim_uni_lead,
    trim_uni_trail    =&gt; \&amp;Validator::Custom::Constraint::trim_uni_trail
  );
  
  return $self;
}

sub register_constraint {
  my $self = shift;
  
  # Merge
  my $constraints = ref $_[0] eq 'HASH' ? $_[0] : {@_};
  $self-&gt;constraints({%{$self-&gt;constraints}, %$constraints});
  
  return $self;
}

our %VALID_OPTIONS = map {$_ =&gt; 1} qw/message default copy require/;

sub validate {
  my ($self, $data, $rule) = @_;
  
  # Class
  my $class = ref $self;
  
  # Validation rule
  $rule ||= $self-&gt;rule;
  
  # Data filter
  my $filter = $self-&gt;data_filter;
  $data = $filter-&gt;($data) if $filter;
  
  # Check data
  croak "First argument must be hash ref"
    unless ref $data eq 'HASH';
  
  # Check rule
  unless (ref $rule eq 'Validator::Custom::Rule') {
    croak "Validation rule must be array ref\n" .
        "(see syntax of validation rule 1)\n" .
        $self-&gt;_rule_syntax($rule)
      unless ref $rule eq 'ARRAY';
  }
  
  # Result
  my $result = Validator::Custom::Result-&gt;new;
  $result-&gt;{_error_infos} = {};
  
  # Save raw data
  $result-&gt;raw_data($data);
  
  # Error is stock?
  my $error_stock = $self-&gt;error_stock;
  
  # Valid keys
  my $valid_keys = {};
  
  # Error position
  my $pos = 0;
  
  # Found missing paramteters
  my $found_missing_params = {};
  
  # Shared rule
  my $shared_rule = $self-&gt;shared_rule;
  warn "DBIx::Custom::shared_rule is DEPRECATED!"
    if @$shared_rule;
  
  if (ref $rule eq 'Validator::Custom::Rule') {
    $self-&gt;rule_obj($rule);
  }
  else {
    my $rule_obj = Validator::Custom::Rule-&gt;new;
    $rule_obj-&gt;parse($rule, $shared_rule);
    $self-&gt;rule_obj($rule_obj);
  }
  my $rule_obj = $self-&gt;rule_obj;

  # Process each key
  OUTER_LOOP:
  for (my $i = 0; $i &lt; @{$rule_obj-&gt;rule}; $i++) {
    
    my $r = $rule_obj-&gt;rule-&gt;[$i];
    
    # Increment position
    $pos++;
    
    # Key, options, and constraints
    my $key = $r-&gt;{key};
    my $opts = $r-&gt;{option};
    my $constraints = $r-&gt;{constraints};
    
    # Check constraints
    croak "Constraints of validation rule must be array reference. " .
        "see syntax 2.\n" . $self-&gt;_rule_syntax($rule)
      unless ref $constraints eq 'ARRAY';
    
    # Arrange key
    my $result_key = $key;
    if (ref $key eq 'HASH') {
      my $first_key = (keys %$key)[0];
      $result_key = $first_key;
      $key         = $key-&gt;{$first_key};
    }
    
    # Real keys
    my $keys;
    
    if (ref $key eq 'ARRAY') { $keys = $key }
    elsif (ref $key eq 'Regexp') {
      $keys = [];
      for my $k (keys %$data) {
         push @$keys, $k if $k =~ /$key/;
      }
    }
    else { $keys = [$key] }
    
    # Check option
    for my $oname (keys %$opts) {
      croak qq{Option "$oname" of "$result_key" is invalid name}
        unless $VALID_OPTIONS{$oname};
    }
    
    # Is data copy?
    my $copy = 1;
    $copy = $opts-&gt;{copy} if exists $opts-&gt;{copy};
    
    # Check missing parameters
    my $require = exists $opts-&gt;{require} ? $opts-&gt;{require} : 1;
    my $found_missing_param;
    my $missing_params = $result-&gt;missing_params;
    for my $key (@$keys) {
      unless (exists $data-&gt;{$key}) {
        if ($require) {
          push @$missing_params, $key
            unless $found_missing_params-&gt;{$key};
          $found_missing_params-&gt;{$key}++;
        }
        $found_missing_param = 1;
      }
    }
    if ($found_missing_param) {
      $result-&gt;data-&gt;{$result_key} = ref $opts-&gt;{default} eq 'CODE'
          ? $opts-&gt;{default}-&gt;($self) : $opts-&gt;{default}
        if exists $opts-&gt;{default} &amp;&amp; $copy;
      next if $opts-&gt;{default} || !$require;
    }
    
    # Already valid
    next if $valid_keys-&gt;{$result_key};
    
    # Validation
    my $value = @$keys &gt; 1
      ? [map { $data-&gt;{$_} } @$keys]
      : $data-&gt;{$keys-&gt;[0]};

    for my $c (@$constraints) {
      
      # Arrange constraint information
      my $constraint = $c-&gt;{constraint};
      my $message = $c-&gt;{message};
      
      # Data type
      my $data_type = {};
      
      # Arguments
      my $arg;
      
      # Arrange constraint
      if(ref $constraint eq 'HASH') {
        my $first_key = (keys %$constraint)[0];
        $arg        = $constraint-&gt;{$first_key};
        $constraint = $first_key;
      }
      
      # Constraint function
      my $cfuncs;
      my $negative;
      
      # Sub reference
      if( ref $constraint eq 'CODE') {
        # Constraint function
        $cfuncs = [$constraint];
      }
      
      # Constraint key
      else {
        # Constirnt infomation
        my $cinfo = $self-&gt;_parse_constraint($constraint);
        $data_type-&gt;{array} = 1 if $cinfo-&gt;{array};
                                        
        # Constraint function
        $cfuncs = $cinfo-&gt;{funcs};
      }
      
      # Is valid?
      my $is_valid;
      
      # Data is array
      if($data_type-&gt;{array}) {
          
        # To array
        $value = [$value] unless ref $value eq 'ARRAY';
        
        # Validation loop
        for (my $k = 0; $k &lt; @$value; $k++) {
          my $data = $value-&gt;[$k];
          
          # Validation
          for (my $j = 0; $j &lt; @$cfuncs; $j++) {
            my $cfunc = $cfuncs-&gt;[$j];
            
            # Validate
            my $cresult = $cfunc-&gt;($data, $arg, $self);
            
            # Constrint result
            my $v;
            if (ref $cresult eq 'ARRAY') {
              ($is_valid, $v) = @$cresult;
              $value-&gt;[$k] = $v;
            }
            elsif (ref $cresult eq 'HASH') {
              $is_valid = $cresult-&gt;{result};
              $message = $cresult-&gt;{message} unless $is_valid;
              $value-&gt;[$k] = $cresult-&gt;{output} if exists $cresult-&gt;{output};
            }
            else { $is_valid = $cresult }
            
            last if $is_valid;
          }
          
          # Validation error
          last unless $is_valid;
        }
      }
      
      # Data is scalar
      else {
        # Validation
        for my $cfunc (@$cfuncs) {
          my $cresult = $cfunc-&gt;($value, $arg, $self);
          
          if (ref $cresult eq 'ARRAY') {
            my $v;
            ($is_valid, $v) = @$cresult;
            $value = $v if $is_valid;
          }
          elsif (ref $cresult eq 'HASH') {
            $is_valid = $cresult-&gt;{result};
            $message = $cresult-&gt;{message} unless $is_valid;
            $value = $cresult-&gt;{output} if exists $cresult-&gt;{output} &amp;&amp; $is_valid;
          }
          else { $is_valid = $cresult }
          
          last if $is_valid;
        }
      }
      
      # Add error if it is invalid
      unless ($is_valid) {
        # Resist error info
        $message = $opts-&gt;{message} unless defined $message;
        $result-&gt;{_error_infos}-&gt;{$result_key} = {
          message      =&gt; $message,
          position     =&gt; $pos,
          reason       =&gt; $constraint,
          original_key =&gt; $key
        } unless exists $result-&gt;{_error_infos}-&gt;{$result_key};
        
        # Set default value
        $result-&gt;data-&gt;{$result_key} = ref $opts-&gt;{default} eq 'CODE'
                                     ? $opts-&gt;{default}-&gt;($self)
                                     : $opts-&gt;{default}
          if exists $opts-&gt;{default} &amp;&amp; $copy;
        
        # No Error strock
        unless ($error_stock) {
          # Check rest constraint
          my $found;
          for (my $k = $i + 1; $k &lt; @{$rule_obj-&gt;rule}; $k++) {
            my $r_next = $rule_obj-&gt;rule-&gt;[$k];
            my $key_next = $r_next-&gt;{key};
            $key_next = (keys %$key)[0] if ref $key eq 'HASH';
            $found = 1 if $key_next eq $result_key;
          }
          last OUTER_LOOP unless $found;
        }
        next OUTER_LOOP;
      }
    }
    
    # Result data
    $result-&gt;data-&gt;{$result_key} = $value if $copy;
    
    # Key is valid
    $valid_keys-&gt;{$result_key} = 1;
    
    # Remove invalid key
    delete $result-&gt;{_error_infos}-&gt;{$key};
  }
  
  return $result;
}

sub _parse_constraint {
  my ($self, $constraint) = @_;
  
  # Constraint infomation
  my $cinfo = {};
  
  # Simple constraint name
  unless ($constraint =~ /\W/) {
    my $cfunc = $self-&gt;constraints-&gt;{$constraint} || '';
    croak qq{"$constraint" is not registered}
      unless ref $cfunc eq 'CODE';
    $cinfo-&gt;{funcs} = [$cfunc];
    return $cinfo;
  }

  # Trim space
  $constraint ||= '';
  $constraint =~ s/^\s+//;
  $constraint =~ s/\s+$//;
  
  # Target is array elemetns
  $cinfo-&gt;{array} = 1 if $constraint =~ s/^@//;
  croak qq{"\@" must be one at the top of constrinat name}
    if index($constraint, '@') &gt; -1;
  
  # Constraint functions
  my @cfuncs;
  
  # Constraint names
  my @cnames = split(/\|\|/, $constraint);
  
  # Convert constarint names to constraint funcions
  for my $cname (@cnames) {
    $cname ||= '';
    
    # Trim space
    $cname =~ s/^\s+//;
    $cname =~ s/\s+$//;
    
    # Negative
    my $negative = $cname =~ s/^!// ? 1 : 0;
    croak qq{"!" must be one at the top of constraint name}
      if index($cname, '!') &gt; -1;
    
    # Trim space
    $cname =~ s/^\s+//;
    $cname =~ s/\s+$//;
    
    # Constraint function
    croak "Constraint name '$cname' must be [A-Za-z0-9_]"
      if $cname =~ /\W/;
    my $cfunc = $self-&gt;constraints-&gt;{$cname} || '';
    croak qq{"$cname" is not registered}
      unless ref $cfunc eq 'CODE';
    
    # Negativate
    my $f = $negative ? sub {
      my $ret = $cfunc-&gt;(@_);
      if (ref $ret eq 'ARRAY') {
        $ret-&gt;[0] = ! $ret-&gt;[0];
        return $ret;
      }
      else { return !$ret }
    } : $cfunc;
    
    # Add
    push @cfuncs, $f;
  }
  
  $cinfo-&gt;{funcs} = \@cfuncs;
  
  return $cinfo;
}

sub _parse_random_string_rule {
  my $self = shift;
  
  # Rule
  my $rule = ref $_[0] eq 'HASH' ? $_[0] : {@_};
  
  # Result
  my $result = {};
  
  # Parse string rule
  for my $name (keys %$rule) {
    # Pettern
    my $pattern = $rule-&gt;{$name};
    $pattern = '' unless $pattern;
    
    # State
    my $state = 'character';

    # Count
    my $count = '';
    
    # Chacacter sets
    my $csets = [];
    my $cset = [];
    
    # Parse pattern
    my $c;
    while (defined ($c = substr($pattern, 0, 1, '')) &amp;&amp; length $c) {
      # Character class
      if ($state eq 'character_class') {
        if ($c eq ']') {
          $state = 'character';
          push @$csets, $cset;
          $cset = [];
          $state = 'character';
        }
        else { push @$cset, $c }
      }
      
      # Count
      elsif ($state eq 'count') {
        if ($c eq '}') {
          $count = 1 if $count &lt; 1;
          for (my $i = 0; $i &lt; $count - 1; $i++) {
              push @$csets, [@{$csets-&gt;[-1] || ['']}];
          }
          $count = '';
          $state = 'character';
        }
        else { $count .= $c }
      }
      
      # Character
      else {
        if ($c eq '[') { $state = 'character_class' }
        elsif ($c eq '{') { $state = 'count' }
        else { push @$csets, [$c] }
      }
    }
    
    # Add Charcter sets
    $result-&gt;{$name} = $csets;
  }
  
  return $result;
}

sub _rule_syntax {
  my $self = shift;
  
  my $message = $self-&gt;syntax;
  require Data::Dumper;
  my $rule_obj = $self-&gt;rule_obj;
  if ($rule_obj) {
    $message .= "### Rule is interpreted as the follwoing data structure\n";
    $message .= Data::Dumper-&gt;Dump([$rule_obj-&gt;rule], ['$rule']);
  }
  
  return $message;
}

# DEPRECATED!
has shared_rule =&gt; sub { [] };
# DEPRECATED!
__PACKAGE__-&gt;dual_attr('constraints',
  default =&gt; sub { {} }, inherit =&gt; 'hash_copy');

1;

=head1 NAME

Validator::Custom - HTML form Validation, easy and flexibly

=head1 SYNOPSYS

  use Validator::Custom;
  my $vc = Validator::Custom-&gt;new;
  
  # Data
  my $data = {age =&gt; 19, name =&gt; 'Ken Suzuki'};
  
  # Rule
  my $rule = [
    age =&gt; [
      ['not_blank' =&gt; 'age is empty.'],
      ['int' =&gt; 'age must be integer']
    ],
    name =&gt; [
      ['not_blank' =&gt; 'name is emtpy'],
      [{length =&gt; [1, 5]} =&gt; 'name is too long']
    ]
  ];
  
  # Validation
  my $result = $vc-&gt;validate($data, $rule);
  if ($result-&gt;is_ok) {
    # Safety data
    my $safe_data = $vresult-&gt;data;
  }
  else {
    # Error messgaes
    my $errors = $vresult-&gt;messages;
  }

=head1 DESCRIPTION

L&lt;Validator::Custom&gt; validate HTML form data easy and flexibly.
The features are the following ones.

=over 4

=item *

Many constraint functions are available by default, such as C&lt;not_blank&gt;,
C&lt;int&gt;, C&lt;defined&gt;, C&lt;in_array&gt;, C&lt;length&gt;.

=item *

Several filter functions are available by default, such as C&lt;trim&gt;,
C&lt;datetime_to_timepiece&gt;, C&lt;date_to_timepiece&gt;.

=item *

You can register your constraint function.

=item *

You can set error messages for invalid parameter value.
The order of messages is keeped.

=item *

Support C&lt;OR&gt; condtion constraint and negativate constraint,

=back

=head1 GUIDE

L&lt;Validator::Custom::Guide&gt; - L&lt;Validator::Custom&gt; Guide

=head1 ATTRIBUTES

=head2 constraints

  my $constraints = $vc-&gt;constraints;
  $vc             = $vc-&gt;constraints(\%constraints);

Constraint functions.

=head2 data_filter

  my $filter = $vc-&gt;data_filter;
  $vc        = $vc-&gt;data_filter(\&amp;data_filter);

Filter for input data. If data is not hash reference, you can convert
the data to hash reference.

  $vc-&gt;data_filter(sub {
    my $data = shift;
    
    my $hash = {};
    
    # Convert data to hash reference
    
    return $hash;
  });

=head2 error_stock

  my $error_stock = $vc-&gt;error_stcok;
  $vc             = $vc-&gt;error_stock(1);

If error_stock is set to 0, C&lt;validate()&gt; return soon after invalid value is found.

Default to 1. 

=head2 rule_obj EXPERIMENTAL

  my $rule_obj = $vc-&gt;rule_obj($rule);

L&lt;Validator::Custom&gt; rule is a little complex.
You maybe make mistakes offten.
If you want to know that how Validator::Custom parse rule,
See C&lt;rule_obj&gt; attribute after calling C&lt;validate&gt; method.
This is L&lt;Validator::Custom::Rule&gt; object.
  
  my $vresult = $vc-&gt;validate($data, $rule);

  use Data::Dumper;
  print Dumper $vc-&gt;rule_obj-&gt;rule;

If you see C&lt;ERROR&gt; key, rule syntx is wrong.

=head2 rule

  my $rule = $vc-&gt;rule;
  $vc      = $vc-&gt;rule(\@rule);

Validation rule. If second argument of C&lt;validate()&gt; is not specified.
this rule is used.

=head2 syntax

  my $syntax = $vc-&gt;syntax;
  $vc        = $vc-&gt;syntax($syntax);

Syntax of rule.

=head1 METHODS

L&lt;Validator::Custom&gt; inherits all methods from L&lt;Object::Simple&gt;
and implements the following new ones.

=head2 new

  my $vc = Validator::Custom-&gt;new;

Create a new L&lt;Validator::Custom&gt; object.

=head2 js_fill_form_button

  my $button = $self-&gt;js_fill_form_button(
    mail =&gt; '[abc]{3}@[abc]{2}.com,
    title =&gt; '[pqr]{5}'
  );

Create javascript button source code to fill form.
You can specify string or pattern like regular expression.

If you click this button, each text box is filled with the
specified pattern string,
and checkbox, radio button, and list box is automatically selected.

Note that this methods require L&lt;JSON&gt; module.

=head2 validate

  $result = $vc-&gt;validate($data, $rule);
  $result = $vc-&gt;validate($data);

Validate the data.
Return value is L&lt;Validator::Custom::Result&gt; object.
If second argument isn't passed, C&lt;rule&gt; attribute is used as rule.

$rule is array refernce
(or L&lt;Validator::Custom::Rule&gt; object, this is EXPERIMENTAL).

=head2 register_constraint

  $vc-&gt;register_constraint(%constraint);
  $vc-&gt;register_constraint(\%constraint);

Register constraint function.
  
  $vc-&gt;register_constraint(
    int =&gt; sub {
      my $value    = shift;
      my $is_valid = $value =~ /^\-?[\d]+$/;
      return $is_valid;
    },
    ascii =&gt; sub {
      my $value    = shift;
      my $is_valid = $value =~ /^[\x21-\x7E]+$/;
      return $is_valid;
    }
  );

You can register filter function.

  $vc-&gt;register_constraint(
    trim =&gt; sub {
      my $value = shift;
      $value =~ s/^\s+//;
      $value =~ s/\s+$//;
      
      return [1, $value];
    }
  );

Filter function return array reference,
first element is the value if the value is valid or not,
second element is the converted value by filter function.

=head1 RULE SYNTAX

Validation rule has the following syntax.

  # Rule syntax
  my $rule = [                          # 1 Rule is array ref
    key =&gt; [                            # 2 Constraints is array ref
      'constraint',                     # 3 Constraint is string
      {'constraint' =&gt; 'args'}          #     or hash ref (arguments)
      ['constraint', 'err'],            #     or arrya ref (message)
    ],
    key =&gt; [                           
      [{constraint =&gt; 'args'}, 'err']   # 4 With argument and message
    ],
    {key =&gt; ['key1', 'key2']} =&gt; [      # 5.1 Multi-parameters validation
      'constraint'
    ],
    {key =&gt; qr/^key/} =&gt; [              # 5.2 Multi-parameters validation
      'constraint'                            using regular expression
    ],
    key =&gt; [
      '@constraint'                     # 6 Multi-values validation
    ],
    key =&gt; {message =&gt; 'err', ... } =&gt; [# 7 With option
      'constraint'
    ],
    key =&gt; [
      '!constraint'                     # 8 Negativate constraint
    ],
    key =&gt; [
      'constraint1 || constraint2'      # 9 "OR" condition constraint
    ],
  ];

Rule can have option, following options is available.

=over 4

=item 1. message

  {message =&gt; "Input right value"}

Message for invalid value.

=item 2. default

  {default =&gt; 5}

Default value, set to C&lt;data&gt; of C&lt;Validator::Custom::Result&gt;
when invalid value or missing value is found

=item 3. copy

  {copy =&gt; 0}

If C&lt;copy&gt; is 0, the value is not copied to C&lt;data&gt; of C&lt;Validator::Custom::Result&gt;. 

Default to 1. 

=item 4. require

  {require =&gt; 0}

If C&lt;require&gt; is 0,
The value is not appended to missing parameter list
even if the value is not found

Default to 1.

=back

=head1 CONSTRAINTS

=head2 ascii

  my $data =&gt; {name =&gt; 'Ken'};
  my $rule = [
    name =&gt; [
      'ascii'
    ]
  ];

Ascii graphic characters(hex 21-7e).

=head2 between

  my $data = {age =&gt; 19};
  my $rule = [
    age =&gt; [
      {between =&gt; [1, 20]} # (1, 2, .. 19, 20)
    ]
  ];

Between A and B.

=head2 blank

  my $data = {name =&gt; ''};
  my $rule = [
    name =&gt; [
      'blank'
    ]
  ];

Blank.

=head2 decimal
  
  my $data = {num1 =&gt; '123', num2 =&gt; '1.45'};
  my $rule =&gt; [
    num1 =&gt; [
      {'decimal' =&gt; 3}
    ],
    num2 =&gt; [
      {'decimal' =&gt; [1, 2]}
    ]
  ];

Decimal. You can specify maximus digits number at before
and after '.'.

=head2 defined

  my $data =&gt; {name =&gt; 'Ken'};
  my $rule = [
    name =&gt; [
      'defined'
    ]
  ];

Defined.

=head2 duplication

  my $data = {mail1 =&gt; 'a@somehost.com', mail2 =&gt; 'a@somehost.com'};
  my $rule =&gt; [
    {mail =&gt; ['mail1', 'mail2']} =&gt; [
      'duplication'
    ]
  ];

Check if the two data are same or not.

Note that if one value is not defined or both values are not defined,
result of validation is false.

=head2 equal_to

  my $data = {price =&gt; 1000};
  my $rule = [
    price =&gt; [
      {'equal_to' =&gt; 1000}
    ]
  ];

Numeric equal comparison.

=head2 greater_than

  my $data = {price =&gt; 1000};
  my $rule = [
    price =&gt; [
      {'greater_than' =&gt; 900}
    ]
  ];

Numeric "greater than" comparison

=head2 http_url

  my $data = {url =&gt; 'http://somehost.com'};
  my $rule =&gt; [
    url =&gt; [
      'http_url'
    ]
  ];

HTTP(or HTTPS) URL.

=head2 int

  my $data = {age =&gt; 19};
  my $rule = [
    age =&gt; [
      'int'
    ]
  ];

Integer.

=head2 in_array

  my $data = {food =&gt; 'sushi'};
  my $rule = [
    food =&gt; [
      {'in_array' =&gt; [qw/sushi bread apple/]}
    ]
  ];

Check if the values is in array.

=head2 length

  my $data = {value1 =&gt; 'aaa', value2 =&gt; 'bbbbb'};
  my $rule =&gt; [
    value1 =&gt; [
      # length is equal to 3
      {'length' =&gt; 3} # 'aaa'
    ],
    value2 =&gt; [
      # length is greater than or equal to 2 and lower than or equeal to 5
      {'length' =&gt; [2, 5]} # 'bb' to 'bbbbb'
    ]
    value3 =&gt; [
      # length is greater than or equal to 2 and lower than or equeal to 5
      {'length' =&gt; {min =&gt; 2, max =&gt; 5}} # 'bb' to 'bbbbb'
    ]
    value4 =&gt; [
      # greater than or equal to 2
      {'length' =&gt; {min =&gt; 2}}
    ]
    value5 =&gt; [
      # lower than or equal to 5
      {'length' =&gt; {max =&gt; 5}}
    ]
  ];

Length of the value.

Not that if value is internal string, length is character length.
if value is byte string, length is byte length.

=head2 less_than

  my $data = {num =&gt; 20};
  my $rule = [
    num =&gt; [
      {'less_than' =&gt; 25}
    ]
  ];

Numeric "less than" comparison.

=head2 not_blank

  my $data = {name =&gt; 'Ken'};
  my $rule = [
    name =&gt; [
      'not_blank' # Except for ''
    ]
  ];

Not blank.

=head2 not_defined

  my $data = {name =&gt; 'Ken'};
  my $rule = [
    name =&gt; [
      'not_defined'
    ]
  ];

Not defined.

=head2 not_space

  my $data = {name =&gt; 'Ken'};
  my $rule = [
    name =&gt; [
      'not_space' # Except for '', ' ', '   '
    ]
  ];

Not contain only space characters. 
Not that space is only C&lt;[ \t\n\r\f]&gt;
which don't contain unicode space character.

=head2 space

  my $data = {name =&gt; '   '};
  my $rule = [
    name =&gt; [
      'space' # '', ' ', '   '
    ]
  ];

White space or empty stirng.
Not that space is only C&lt;[ \t\n\r\f]&gt;
which don't contain unicode space character.

=head2 uint

  my $data = {age =&gt; 19};
  my $rule = [
    age =&gt; [
      'uint'
    ]
  ];

Unsigned integer(contain zero).
  
=head2 regex

  my $data = {num =&gt; '123'};
  my $rule =&gt; [
    num =&gt; [
      {'regex' =&gt; qr/\d{0,3}/}
    ]
  ];

Match a regular expression.

=head2 selected_at_least

  my $data = {hobby =&gt; ['music', 'movie' ]};
  my $rule =&gt; [
    hobby =&gt; [
      {selected_at_least =&gt; 1}
    ]
  ];

Selected at least specified count item.
In other word, the array contains at least specified count element.

=head1 FILTERS

=head2 date_to_timepiece

  my $data = {date =&gt; '2010/11/12'};
  my $rule = [
    date =&gt; [
      'date_to_timepiece'
    ]
  ];

The value which looks like date is converted
to L&lt;Time::Piece&gt; object.
If the value contains 8 digits, the value is assumed date.

  2010/11/12 # ok
  2010-11-12 # ok
  20101112   # ok
  2010       # NG
  2010111106 # NG

And year and month and mday combination is ok.

  my $data = {year =&gt; 2011, month =&gt; 3, mday =&gt; 9};
  my $rule = [
    {date =&gt; ['year', 'month', 'mday']} =&gt; [
      'date_to_timepiece'
    ]
  ];

Note that L&lt;Time::Piece&gt; is required.

=head2 datetime_to_timepiece

  my $data = {datetime =&gt; '2010/11/12 12:14:45'};
  my $rule = [
    datetime =&gt; [
      'datetime_to_timepiece'
    ]
  ];

The value which looks like date and time is converted
to L&lt;Time::Piece&gt; object.
If the value contains 14 digits, the value is assumed date and time.

  2010/11/12 12:14:45 # ok
  2010-11-12 12:14:45 # ok
  20101112 121445     # ok
  2010                # NG
  2010111106 12       # NG

And year and month and mday combination is ok.

  my $data = {year =&gt; 2011, month =&gt; 3, mday =&gt; 9
              hour =&gt; 10, min =&gt; 30, sec =&gt; 30};
  my $rule = [
    {datetime =&gt; ['year', 'month', 'mday', 'hour', 'min', 'sec']} =&gt; [
      'datetime_to_timepiece'
    ]
  ];

Note that L&lt;Time::Piece&gt; is required.

=head2 merge

  my $data = {name1 =&gt; 'Ken', name2 =&gt; 'Rika', name3 =&gt; 'Taro'};
  my $rule = [
    {merged_name =&gt; ['name1', 'name2', 'name3']} =&gt; [
      'merge' # KenRikaTaro
    ]
  ];

Merge the values.
Note that if one value is not defined, merged value become undefined.

=head2 shift

  my $data = {names =&gt; ['Ken', 'Taro']};
  my $rule =&gt; [
    names =&gt; [
      'shift' # 'Ken'
    ]
  ];

Shift the head element of array.

=head2 to_array

  my $data = {languages =&gt; 'Japanese'};
  my $rule = [
    languages =&gt; [
      'to_array' # ['Japanese']
    ],
  ];
  
Convert non array reference data to array reference.
This is useful to check checkbox values or select multiple values.

=head2 trim

  my $data = {name =&gt; '  Ken  '};
  my $rule = [
    name =&gt; [
      'trim' # 'Ken'
    ]
  ];

Trim leading and trailing white space.
Not that trim only C&lt;[ \t\n\r\f]&gt;
which don't contain unicode space character.

=head2 trim_collapse

  my $data = {name =&gt; '  Ken   Takagi  '};
  my $rule = [
    name =&gt; [
      'trim_collapse' # 'Ken Takagi'
    ]
  ];

Trim leading and trailing white space,
and collapse all whitespace characters into a single space.
Not that trim only C&lt;[ \t\n\r\f]&gt;
which don't contain unicode space character.

=head2 trim_lead

  my $data = {name =&gt; '  Ken  '};
  my $rule = [
    name =&gt; [
      'trim_lead' # 'Ken  '
    ]
  ];

Trim leading white space.
Not that trim only C&lt;[ \t\n\r\f]&gt;
which don't contain unicode space character.

=head2 trim_trail

  my $data = {name =&gt; '  Ken  '};
  my $rule = [
    name =&gt; [
      'trim_trail' # '  Ken'
    ]
  ];

Trim trailing white space.
Not that trim only C&lt;[ \t\n\r\f]&gt;
which don't contain unicode space character.

=head2 trim_uni

  my $data = {name =&gt; '  Ken  '};
  my $rule = [
    name =&gt; [
      'trim_uni' # 'Ken'
    ]
  ];

Trim leading and trailing white space, which contain unicode space character.

=head2 trim_uni_collapse

  my $data = {name =&gt; '  Ken   Takagi  '};
  my $rule = [
    name =&gt; [
      'trim_uni_collapse' # 'Ken Takagi'
    ]
  ];

Trim leading and trailing white space, which contain unicode space character.

=head2 trim_uni_lead

  my $data = {name =&gt; '  Ken  '};
  my $rule = [
    name =&gt; [
      'trim_uni_lead' # 'Ken  '
    ]
  ];

Trim leading white space, which contain unicode space character.

=head2 trim_uni_trail

  my $data = {name =&gt; '  Ken  '};
  my $rule = [
    name =&gt; [
      'trim_uni_trail' # '  Ken'
    ]
  ];

Trim trailing white space, which contain unicode space character.

=head1 DEPRECATED FUNCTIONALITIES

L&lt;Validator::Custom&gt;
  
  # Atrribute methods
  shared_rule # Removed at 2017/1/1
  
  # Methods
  __PACKAGE__-&gt;constraints(...); # Call constraints method as class method
                                 # Removed at 2017/1/1
L&lt;Validator::Custom::Result&gt;

  # Attribute methods
  error_infos # Removed at 2017/1/1 

  # Methods
  add_error_info # Removed at 2017/1/1
  error # Removed at 2017/1/1
  errors # Removed at 2017/1/1
  errors_to_hash # Removed at 2017/1/1
  invalid_keys # Removed at 2017/1/1
  remove_error_info# Removed at 2017/1/1

=head1 BACKWORD COMPATIBLE POLICY

If a functionality is DEPRECATED, you can know it by DEPRECATED warnings.
DEPRECATED functionality is removed after five years,
but if at least one person use the functionality and tell me that thing
I extend one year each time you tell me it.

EXPERIMENTAL functionality will be changed without warnings.

=head1 AUTHOR

Yuki Kimoto, C&lt;&lt; &lt;kimoto.yuki at gmail.com&gt; &gt;&gt;

L&lt;http://github.com/yuki-kimoto/Validator-Custom&gt;

=head1 COPYRIGHT &amp; LICENCE

Copyright 2009-2013 Yuki Kimoto, all rights reserved.

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

=cut
</pre></body></html>