in reply to Need help with regexes to validate user input

1. alphabetical characters check

if ($who !~ /[A-Za-z]/) ... # thanks to eric256 to point out the prob +lem if ($who2 !~ /[A-Za-z]/) ... # in my regexp. I really meant to use a n +egative # regexp. If any character not alphabetic +al. ^_^
2. email address validation

if ($email =~ /@/) ...
Ok, what I did was perhaps too simple here. You should really use the Mail::Address module to check/obtain the canonical form of the Email address properly.

3. credit card number should only contain 16 characters

if ($creditcard =~ /^\d{16}$/) ...
Assume no space in the credit card number. Otherwise a simple check to strip out the space. Thanks to hardburn to point out the credit card checking modules. I was a bit lazy because Audrey Fong only wanted to check if there were 16 digits.

Replies are listed 'Best First'.
Re: Re: Audrey Fong
by hardburn (Abbot) on Nov 11, 2003 at 15:02 UTC

    3. credit card number should only contain 16 characters

    if ($creditcard =~ /^\d{16}$/) ...

    Assume no space in the credit card number. Otherwise a simple check to strip out the space.

    Actually, for CC validation, use Buisness::CreditCard. A CC num isn't necessiarily 16 digits (it changes between companies), the first few digits identify the company, and the last digit is a checksum. Buisness::CreditCard will look at all these things for you.

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    : () { :|:& };:

    Note: All code is untested, unless otherwise stated

Re: Re: Audrey Fong
by eric256 (Parson) on Nov 11, 2003 at 17:45 UTC

    That name solution just checkes to see if there are letters in it, not that there are only letters in it. One regex to test that would be $who =~ /^([a-zA-Z])$/. That would give you the flexibility to later require it to start or end with certain letters, allow a - in the middle or a .

    Example of how the two regex differ when matching a string.

    use strict; my $test1 = "abcd"; print "Testing: $test1\n"; print "Passed #1\n" if ($test1 =~ /[A-Za-z]/); print "Passed #2\n" if ($test1 =~ /^([A-Za-z])*$/); $test1 = "abcd1234"; print "\nTesting: $test1\n"; print "Passed #1\n" if ($test1 =~ /[A-Za-z]/); print "Passed #2\n" if ($test1 =~ /^([A-Za-z])*$/); # output __DATA__ Testing: abcd Passed #1 Passed #2 Testing: abcd1234 Passed #1

    ___________
    Eric Hodges