Enforcing Data Rules


You will often want to ensure not only that data is entered into required fields but that the quality of the data is good enough before proceeding. For instance, you might want to check that an email address or a phone number has the right format, using the rules developed in Lesson 8, "Regular Expressions." You could also enforce a minimum length on a field to make sure a user cannot just enter an x in each field to continue to the next page.

Because each field will probably have a different validation rule, you cannot enforce data rules in a loop; you must instead write a rule for each field to be checked. However, when used in conjunction with the check for empty fields in a loop from the previous examples, you should also check that the value has been entered before doing any further validation. Otherwise, the warning message will first tell a user that a field is required and then also that it has been entered in the wrong format!

The following rules could be added to Listing 13.1 after the required fields check to enforce suitable values for email address and telephone number:

 if ($_POST["email"] &&   !ereg("^[^@]+@([a-z0-9\-]+\.)+[a-z]{2,4}$",       $_POST["email"]))   $err .= "Email address format was incorrect <br>"; if ($_POST["telephone"] &&   !ereg("^\([[:digit:]]{3}\)[[:digit:]]{3}-[[:digit:]]{4}$",       $_POST["telephone"]))   $err .= "Telephone must be in format (555)555-5555 <br>"; 

Because these additional rules add new messages to $err if an error is found, the rest of the script remains unchanged.



    Sams Teach Yourself PHP in 10 Minutes
    Sams Teach Yourself PHP in 10 Minutes
    ISBN: 0672327627
    EAN: 2147483647
    Year: 2005
    Pages: 151
    Authors: Chris Newman

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net