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>

Short URL for this post: http://bit.ly/9Gov7g