Release of Validator::Custom 1.01. more simple and more flexible interface is added

I released Validator::Custom 1.01. More simple and more flexible interface is added.
Document is rewrited completely. Backword compatible is kept completely.


Validator::Custom

  • Checking functions and filtering functions is added. You can use these in your source code.
  • A validation object which save the result of validation is added.

Usage

 You can use checking function and filtering functions. The validation result is saved to the validation object. You don't need to learn complex things.

  use Validator::Custom;
  my $vc = Validator::Custom->new;
  
  # Input data
  my $id = 1;
  my $name = 'Ken Suzuki';
  my $price = ' 19.23 ';
  my $favorite = ['001', '002'];
  
  # Create validation object
  my $validation = $vc->validation;
  
  # Check if id is integer
  if (!$vc->check($id, 'int')) {
    # Add failed message
    $validation->add_failed(id => 'id must be integer');
  }
  
  # Check if name has length
  if (!(length $name)) {
    $validation->add_failed(name => 'name must have length');
  }
  # Check if name's length is less than 30
  elsif (!(length $name < 30)) {
    $validation->add_failed(name => 'name is too long');
  }
  
  # Filter price to remove left-rigth space
  $price = $vc->filter($price, 'trim');

# Check price is number and the digits of the decimal part is two or less than two
if (!$vc->check($price, 'number', {decimal_part_max => 2})) {
# Set default value if validation fail
$price = 20.25;
}

# Filter each value of favorite using "trim" filtering function
$favorite = $vc->filter_each($favorite, 'trim');

# Check if favorite has at least one values
if (@$favorite == 0) {
$validation->add_failed(favorite => 'favorite must be selected more than one');
}
# Check if favorite is one of the specified values
elsif (!($vc->check_each($favorite, 'in', ['001', '002', '003']))) {
$validation->add_failed(favorite => 'favorite is invalid');
}

# Check if validation result is valid
if ($validation->is_valid) {
# ...
}
else {

# Check what parameter fail
unless ($validation->is_valid('name')) {
# ...
}

# Get all failed parameter names
my $failed = $validation->failed;

# Get a failed parameter message
my $name_message = $validation->message('name');

# Get all failed parameter messages
my $messages = $validation->messages;

# Get all failed parameter names and the messages as hash reference
my $messages_h = $validation->messages_to_hash;
}


Leave a comment

About Yuki Kimoto

user-pic I'm Perl Programmer. I LOVE Perl. I want to contribute Perl community and Perl users.