#!/usr/bin/perl -w
use strict;
# Type: CGI
# Usually I use CGI.pm, but sometimes when I just want to validate data from users I use these two functions :
# get_param()
# validate_form()
#
# Tested on textfields and password_fields
print "Content-type: text/html; charset=iso-8859-1\n\n";
my %data = get_param();
validate_form(\%data);
# I added this line of code to display results
print $_." ----- ".$data{$_}."
" foreach keys %data;
###############################
# function: validate_form() #
###############################
# ERROR when:
#
# - some field's are empty. User didn't fill them # (for example password or login)
# - password and re-password are not the same
sub validate_form {
my $data = shift;
foreach (keys %$data) {
print "EMPTY FIELD !
" if (!$data->{$_});
}
# simply check values that are important for us
print "WRONG PASSWORD !
"if ($data->{'password'} !~ /^$data->{'re-password'}$/);
}
###########################
# function: get_param() #
###########################
# function get all parameters (name - value) from form
# It returns hash ('name' => 'value')
#
# When user enter ' ' [space] function changes it to '_'.
# For example:
# Nick: This is my nick
# (function change it to This_is_my_nick)
# It also change %40 to @
#
# ERROR when:
#
# - user enter different thing than [a-zA-Z0-9-_]
sub get_param {
my $params = <>;
my $err = "WARNING: You can use only numbers and letters a-z A-Z
";
$params =~ s/\+/_/g;
$params =~ s/%40/@/g; # you can use chr() to change hex
print $err if $params =~ /%/g;
return split /&|=/, $params;
}
What's wrong with [cpan://Data::Validate]? Or, for that matter, just using [cpan://CGI] to do the hard parsing work, and validating from there?
#!/bin/perl -T
use CGI;
use Data::Validate ':math';
my $q = CGI->new();
foreach my $p ( $q->param ) {
my $val = $q->param($p);
if ( defined is_alphanumeric($val) ) {
$q->param(-name=>$p, -value=>is_alphanumeric($val)); #untaint!
}
else {
warn "Parameter '$p' is not alphanumeric!"
}
}
Don't reinvent wheels when people have already done the work for you! :-)
perlmonks.org content © perlmonks.org and pro7agon, radiantmatrix
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03