-
Notifications
You must be signed in to change notification settings - Fork 582
Validator Custom
Yuki Kimoto edited this page May 19, 2015
·
7 revisions
See the official Rendering Guide
Validator::Custom is validation tool. You can validate form data easily.
Validator::Custom - CPAN Distribution.
Validator::Custom::Guide - Validator::Custom Guide, description of various usage.
Validator::Custom Wiki - Validator::Custom wiki, contains many exampes.
Examples With Mojolicious or Mojolicious::Lite.
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 = $vc->create_rule;
$rule->require('name')->check('not_blank')->message('Input Name');
$rule->require('content')->check('not_blank')->message('Input Content');
# 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>
Hey! The above document had some coding errors, which are explained below:
- Around line 90:
-
Non-ASCII character seen before =encoding in 'style="color:red">不正なデータが送信されました。</span>'. Assuming UTF-8