-
Notifications
You must be signed in to change notification settings - Fork 581
Validator Custom
guest20 edited this page May 19, 2017
·
7 revisions
See the official Rendering Guide
HTML form Validation, simple and good flexibility
Validator::Custom - CPAN Distribution.
Validator::Custom Wiki - Validator::Custom wiki, contains many exampes.
Examples with Mojolicious::Lite.
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>