My Blog
My Personal Blog

Restricting an input field to only numbers with preg_match_all() (PHP)

May 7th 2009 in PHP, Programming
This is a pretty easy way to restrict a field to only numbers.
The \D in the preg match is short for [^0-9], which will match all characters, except 0-9.
I'm new to the regex, so there might be a better way to do this.  But this works for me.

I like to do all the validating on the server side, just in case someone has javascript disabled.
<?php
	if(isset($_POST['submit'])) {

		preg_match_all("/\D/i", $_POST['number'], $matches);

		if(!$matches[0][0]) {

			print("Your right " . $_POST['number'] . " is a number!");
				exit;

		}
		else {

			print("That is not a number!");
			exit;
		}

	}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
	<title>Preg Match All</title>
	<meta http-equiv="content-type" content="text/html;charset=utf-8" />
	<meta name="generator" content="Geany 0.18svn" />
</head>

<body>
	<form id="preg_match_all" name="preg_match_all" method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
		Enter a Number : <input type="text" name="number" />
		<input type="submit" value="submit" name="submit" />
	</form>
</body>
</html>

You must be logged in to post a comment.

I run Ubuntu, but I imaging it would probably be the same for most distributions.
Install ndiswrapper, use your repos package search. On Ubuntu it is already installed.

yum search ndiswrapper

or

aptitude search ndiswrapper.

If you need to build from source, check out this post.

Download the driver files here. You can also snag them from the cd [...]

Previous Entry

I’m going to try to actually update this blog on a regular basis from now on.

I know, there are a million posts like this on blogs around the world.

Soon.

Next Entry

Recent Comments