Page 1 of 1

Validation: return only letters/numbers

Posted: Mon Jul 24, 2006 12:22 pm
by Locust
Simply problem but I can't find exactly what I want.

I have an HTML form that puts values from the form into a file. For a few of these values I want it to only accept letters and numbers (no spaces) as well as no symbols. How do I do it?

Thanks :)

Posted: Mon Jul 24, 2006 12:28 pm
by feyd
regular expressions. We have a board dedicated to just that, but before you ask for the solution, try to figure it out yourself by reading the stickies we've got in that board first.

Posted: Mon Jul 24, 2006 12:30 pm
by Locust
Well I figured my problem is too broad and simple - a search engine doesn't know what I'm looking for.

The search continues.

Posted: Mon Jul 24, 2006 12:43 pm
by RobertGonzalez

Posted: Mon Jul 24, 2006 6:22 pm
by Ollie Saunders

Code: Select all

ctype_alnum()
much better than a regular expression because you can't get it wrong.

Posted: Mon Jul 24, 2006 6:26 pm
by Benjamin
ole wrote:

Code: Select all

ctype_alnum()
much better than a regular expression because you can't get it wrong.
Yeah regex isn't need for something this simple. You may want to download a copy of the PHP manual and have a look at all the ctype functions.

Posted: Mon Jul 24, 2006 6:58 pm
by Ollie Saunders
hang just realised that you might want to filter out all the non-alphanumeric characters rather than test for them. In which case you need to use this (this is a regular expression):

Code: Select all

public static function getAlphanumeric($value)
	{
		return preg_replace('/[^[:alnum:]]/', '', $value);
	}
mods: please not this code cannot be put in

Code: Select all

bb tag, it removes the :alnum: bit for some reason.[/b]

Posted: Mon Jul 24, 2006 7:43 pm
by shoebappa
Yeah, I'm a big fan of filtering with ctype when possible.

Posted: Mon Jul 24, 2006 7:44 pm
by shoebappa
Word ole, I'd never seen the :alnum: what other types are there like that? What's that called in regex?

Posted: Tue Jul 25, 2006 1:47 am
by Locust
Thanks for the help. ctype_alnum seems to work the way I want it. Now, however, in another field I want it to allow letters, numbers and spaces. Like ctype_alnum, I'd like to be able to test this rather than replacing values (regular expressions don't seem to test, they just replace) because I want to put this into an if() statement.

Code: Select all

if (ctype_alnum($_POST['field'])) {return true;}
else {return false;}
}
This works fine, now I want to be able to do the same but I want it to allow spaces.

Ty :)

Posted: Tue Jul 25, 2006 2:03 am
by RobertGonzalez
regex functions can match (preg_match(), ereg()).

Posted: Tue Jul 25, 2006 3:13 am
by Ollie Saunders
shoebappa wrote:Word ole, I'd never seen the :alnum: what other types are there like that? What's that called in regex?
Don't know, I only recently saw it myself when it was used in Zend_Filter of the Zend Framework