Samples of regular expression patterns to validate decimals, dutch postal code and an e-mail address


Share Regular expression patterns ver. 1.00

released: 2005-08-07
Regular expressions are often used for data validation together with PHP, Javascript and other programming languages. This examples will show you real world patterns which can be used in PHP with function like preg_match() or ereg() and some other PHP functions. If you need more information about regular expression try a search about "regex" with the Google search engine.

Viewed 16571 times

Rating: script rated with stars
 

<?php
$pattern = "//"; // otherwise you get en error from the preg_match function
if (isset($_POST)) {
    $string = trim($_POST[$_POST['type']]);
    switch($_POST['type']) {
        case "decimal":
        // the next two variables are used to show which values have to be changed to test different types of decimals
        // This example allows a decimal number with max 5 digits before the &quot;.&quot; and 1 or 2 decimals.
        $dec = 2; // the max numbers decimals in front of the "."
        $num = 5 - 1; // the numbers before the "." (minus 1 because there must at minimum one
        $pattern = "/^[1-9]{1}([0-9]{0,".$num."})?\.[0-9]{1,".$dec."}$/"; // 2 decimals
        break;
        // The dutch postal code is a combination of four numbers and 2 letters (f.e. 1000 AB).
        // With this pattern its allowed to use caps and small caps and a single space or not between  numbers and letters.
        case "dutch_pc":
        $pattern = "/^[1-9]{1}[0-9]{3}\s?[a-zA-Z]{2}$/";
        break;
        // This pattern takes care about unallowed characters and combinations.
        case "email":
        $pattern = "/^[\w-]+(\.[\w-]+)*@";
        $pattern .= "([0-9a-z][0-9a-z-]*[0-9a-z]\.)+([a-z]{2,4})$/i";
        break;
    }
    $GLOBALS[$_POST['type']] = (preg_match($pattern, $string)) ? "true" : "false";
}
/* example to test the "email" type
  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <input type="text" name="email" size="20" value="<?php echo (isset($_POST['email'])) ? $_POST['email'] : ""; ?>">
    <input type="hidden" name="type" value="email">
    <input name="submit" type="submit" value="Check!">
    <span class="valid">
    <?php if (isset($GLOBALS['email'])) { echo ($GLOBALS['email'] == "true") ? "OK" : "FALSE"; } ?></span>
  </form>
*/
?>