Page 1 of 1

validate help

Posted: Sat Nov 11, 2006 9:01 pm
by speedy33417
I know it's not a fair request, but I was hoping somebody could help me out with this.

I'm trying to validate two user inputs.

The first ($foo) should only pass if characters used are: a-z 0-9 and -_ (dash and underscore).

The second($bar) only if characters are: a-z A-Z 0-9 -_.,?!&()

This whole ereg thing is a little way too new to me. I've spent about 4 hours on this and I'd rather not post the code I have right now. People would be laughing at it (and me) for years to come...
Puh-please!

Posted: Sat Nov 11, 2006 9:04 pm
by feyd
What have you tried?

Posted: Sat Nov 11, 2006 9:05 pm
by Cameri

Code: Select all

/*The first ($foo) should only pass if characters used are: a-z 0-9 and -_ (dash and underscore).

The second($bar) only if characters are: a-z A-Z 0-9 -_.,?!&() 
*/

// Check if $foo is valid
if (preg_match('![a-z0-9\-_]+!',$foo)) {
 //passed
} else {
// failed
}

// Check if $bar is valid
if (preg_match('![a-z0-9\-_\.,\?!&\(\)]+!i',$bar)) {
 //passed
} else {
// failed
}
Suggestions, read about regular expressions, specially PERL regular expressions, on PHP they are called Perl-Compatible Regular Expressions (PCRE). Google is your best friend.

Posted: Sun Nov 12, 2006 10:58 am
by speedy33417
Thank you for your help Cameri. I tried your code, but I'm getting a strange result.

I think it only checks the first letter, because asd, as@#$ both pass, but @#$ does not.

Here's the code:

Code: Select all

if (preg_match('![a-z0-9\-_]+!',$albumName)) { 
   //passed 
   $message = "passed";
} else { 
   // failed 
   $message = "did not pass";	
}

Posted: Sun Nov 12, 2006 12:02 pm
by Ambush Commander
Cameri's code is close, but incorrect. Use:

Code: Select all

preg_match('!^[a-z0-9\-_]+$!i',$albumName)
and

Code: Select all

preg_match('!^[a-z0-9\-_.,?!&()]+$!i',$bar)
The ^ and $ ensure that the pattern matches the whole string, as running the original regex on "as@#$" matches the "as" and thus returns true, incorrect behavior.

Really, you should check out the tutorial on this forum and get a general idea on how to use regex. They're really powerful and worth learning.

Posted: Sun Nov 12, 2006 2:02 pm
by GeertDD
Quick tip. Ambush Commander already removed the backslashes before the chars within the character class. Note that you don't have to escape the dash neither when you put it right after the opening square bracket of the character class.

Code: Select all

preg_match('!^[-a-z0-9_.,?!&()]+$!i',$bar)