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!
validate help
Moderator: General Moderators
- Cameri
- Forum Commoner
- Posts: 87
- Joined: Tue Apr 12, 2005 4:12 pm
- Location: Santo Domingo, Dominican Republic
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
}- speedy33417
- Forum Contributor
- Posts: 128
- Joined: Sun Jul 23, 2006 1:14 pm
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:
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";
}- Ambush Commander
- DevNet Master
- Posts: 3698
- Joined: Mon Oct 25, 2004 9:29 pm
- Location: New Jersey, US
Cameri's code is close, but incorrect. Use:
and
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.
Code: Select all
preg_match('!^[a-z0-9\-_]+$!i',$albumName)Code: Select all
preg_match('!^[a-z0-9\-_.,?!&()]+$!i',$bar)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.
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)