Simply function that validate user's input.
#!/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{$_}."<br/>" 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 !<br/>" if (!$data->{$_}); } # simply check values that are important for us print "WRONG PASSWORD !<br/>"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<br +/>"; $params =~ s/\+/_/g; $params =~ s/%40/@/g; # you can use chr() to change hex + print $err if $params =~ /%/g; return split /&|=/, $params; }

Replies are listed 'Best First'.
Re: CGI: check Form input
by radiantmatrix (Parson) on Feb 07, 2006 at 17:38 UTC

    What's wrong with Data::Validate? Or, for that matter, just using 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! :-)

    <-radiant.matrix->
    A collection of thoughts and links from the minds of geeks
    The Code that can be seen is not the true Code
    I haven't found a problem yet that can't be solved by a well-placed trebuchet