PDA

View Full Version : validation help


Phip
07-06-2002, 05:35 AM
how can i do you check a string to make sure it is only numbers and letters?

Cloudski
07-06-2002, 06:10 AM
Well, this would make sure they were letters... I would find out how to test if they were numbers, and put another if statement inside this one, or add it on....

If(($variable!>='A' && $varialbe!<='Z')&&($variable!<='a' && $variable!>='z'))
DO THIS.....

I hope I helped a little:)

Phip
07-06-2002, 06:16 AM
yeah...umm...i'll have to stare at that code for a few hours, before it starts to make sense... thanks :thumbsup:

isn't there suppod to be a function??

Ökii
07-06-2002, 01:18 PM
if(preg_match(([a-zA-Z0-9]),$teststring)==1) {echo 'yay';}

Something like that anyway.
Have a gander through the manual and check out regular
expressions and the preg_match() function.

mordred
07-06-2002, 03:52 PM
...hmh... I get a parse error... seems like your delimiters aren't correct? Anyway, you're right, validating strings is done very efficiently by Regular Expressions. Though your example RegExp is not correct, it would validate a string on the first occurence of a letter or number.


$teststring = "foo23foo";

if ( preg_match("/^[a-zA-Z0-9]+$/", $teststring) == 1 ) {
echo 'first method succeeded<br>';
}
if ( preg_match("/[^a-zA-Z0-9]/", $teststring) == 0 ) {
echo 'second method one succeeded';
}


You have two possiblities: Either test if the whole string consists from the start to the end only of [a-zA-Z0-9], as done in the first if-statement, or check for the occurrence of a character that is not included in [a-zA-Z0-9], as done in the second if-statement.
With the first method, your string is ok when you have a match, with the second, the string is only valid when no matches (of forbidden characters) were found, hence you test against 0.

I'd prefer the first RegExp, since it also makes sure that the string isn't empy, which would pass the second method.

hth
mordred

Ökii
07-07-2002, 02:31 PM
hehe, yeah perhaps I should have typed the
something like that anyway bit in bold
on my suggestion. :D

One of these days I'll actually get around to
learning them there regexs better.