Skip to content
guest20 edited this page May 19, 2017 · 7 revisions

Built-in Mojolicious::Validator

See the official Rendering Guide

Validator::Custom

HTML form Validation, simple and good flexibility

CPAN

Validator::Custom - CPAN Distribution.

Wiki

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

Examples

Examples with Mojolicious::Lite.

Simple validation

There are two text box, "name" and "age". "name" must have length. "age" must be integer. 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 $name = param('name');
  my $age = param('age');
  
  # Validation
  $validation = $vc->validation;
  
  # Check name
  if (!length $name) {
    $validation->add_failed(name => 'name must have length');
  }
  
  # Check age
  if (!$vc->check($age, 'int')) {
    $validation->add_failed(age => 'age must be integer');
  }
  
  # Validation is OK
  if ($validation->is_valid) {
    
    # Save data
    # ... by yourself

    # Redirect
    $self->flash(success => 1);
    $self->redirect_to('/');    
  }
  
  # Validation is not OK
  else {
    $self->render(
      'index'
      validation => $validation
    );
  }
};

app->start;

__DATA__

@@ index.html.ep
% my $validation = stash('validation');
<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>
    % }
    <form method="post" action="<%= url_for '/register' %>" >
      <div>
        Name: <input type="text" name="name">
        % if ($validation && !$validation->is_valid('name')) {
          <span style="color:red"><%= $validation->message('name') %></span>
        % }
      </div>
      <div>
        Age: <input type="text" name="age">
        % if ($validation && !$validation->is_valid('age')) {
          <span style="color:red"><%= $validation->message('age') %></span>
        % }
      </div>
      <div><input type="submit" value="Send" ></div>
    </form>
  </body>
</html>
Clone this wiki locally