Skip to content
yuki-kimoto edited this page Mar 26, 2011 · 1 revision

Validator::Custom

Validator::Custom is validation tool. You can validate form data easily.

CPAN

Validator::Custom - CPAN Distribution.

Guide

Validator::Custom::Guide - Validator::Custom Guide, description of various usage.

Wiki

Validator::Custom Wiki - Validator::Custom wiki, contains many exampes.

Examples

Examples With Mojolicious or Mojolicious::Lite.

Simple validation

There are two text box, "name" and "content". These items must be not blank. Framework is Mojolicious::Lite.

use Mojolicious::Lite;
use Validator::Custom;

my $vc = Validator::Custom->new;

get '/' => 'index';

post '/register' => sub {
    my $self = shift;
    
    # Parameter
    my $param = $self->req->params->to_hash;
    
    # Validation Rule
    my $rule = [
        name => {message => 'Input Name'} => [
            'not_blank'
        ],
        content => {message => 'Input Content'} => [
            'not_blank'
        ]
    ];
    
    # Validate
    my $vresult = $vc->validate($param, $rule);
    
    # Validation is OK
    if ($vresult->is_ok) {
        # Get valid data
        my $data = $vresult->data;
        
        # Save data
        # ... by yourself
    
        # Redirect
        $self->flash(success => 1);
        $self->redirect_to('/');    
    }
    
    # Validation is not OK
    else {
      $self->stash(missing => 1) if $vresult->has_missing;
      $self->stash(messages => $vresult->messages_to_hash)
        if $vresult->has_invalid;
      $self->render('index');
    }
};

app->start;

__DATA__

@@ index.html.ep
% my $missing  = stash->{missing};
% my $messages = stash->{messages};
<html>
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
    <title>Validation example 1</title>
  </head>
  <body>
    <h1>BBS</h1>
    % if (flash('success')) {
        <div style="color:blue">OK</div>
    % }
    % if ($missing) {
      <span style="color:red">不正なデータが送信されました。</span>
    % }
    <form method="post" action="<%= url_for '/register' %>" >
      <div>
        Name: <input type="text" name="name">
        % if (my $message = $messages->{name}) {
          <span style="color:red"><%= $message %></span>
        % }
      </div>
      <div>
        Content: <input type="text" name="content">
        % if (my $message = $messages->{content}) {
          <span style="color:red"><%= $message %></span>
        % }
      </div>
      <div><input type="submit" value="Send" ></div>
    </form>
  </body>
</html>

POD ERRORS

Hey! The above document had some coding errors, which are explained below:

Around line 91:

Non-ASCII character seen before =encoding in 'style="color:red">不正なデータが送信されました。</span>'. Assuming UTF-8

Clone this wiki locally