jwlarson3rd has asked for the wisdom of the Perl Monks concerning the following question:

my $name= $p->param('name')||''; if ($name =~ /^([a-zA-Z0-9]+)$/) { $name = $1; # $data now untainted }
I need some help with regular expressions. I would like to restrict $name to large and small case letters and numbers. john larson

Replies are listed 'Best First'.
Re: validating form input
by leira (Monk) on Feb 25, 2004 at 04:03 UTC
    What do you mean by "restrict"? Do you want to replace characters that aren't alphanumeric with something else? Do you simply want to know if the string contains non-alphanumeric characters, so that you can act appropriately?

    Linda

      I would like to delete everything but large and small case letters and numbers john larson
        How about this?

        # replace non alphanumeric characters with '' $name =~ s/\W//g; # replace '_' with '' because \W doesn't catch those $name =~ s/_//g;

        Linda

        perl -e "my $t = \"ABC def 123*GHI;?. jk\"; $t =~ s/([^A-Z0-9 ])*//ig; + print $t;## don't accept any char. except... _______^"
        ...

        ABC def 123GHI jk

        You want the tr (transliteration) operator:

        $name =~ tr/A-Za-z0-9//cd;

         --
        LP^>

Re: validating form input
by chimni (Pilgrim) on Feb 25, 2004 at 04:26 UTC

    you could do something like this if you wanted to restrict a field to a certain set.
    The @wrong array will contain all violating enteries (if you want them in your error msg.
    my $test="%%6ffgg"; die("illegal character found".join(',',@wrong)."\n") if @wrong = $test + =~(m/([^a-zA-Z0-9])/g); output illegal character found%,%

    HTH