PHP Data Validation
From Wiki
This article is a stub. You can help us by expanding it.
Validation is actually two processes: finding errors and presenting error messages.
Finding errors can be interactive, where data is checked as it's entered, or post-validation, where the data is checked after entry.
Presenting errors can be field-by-field—where a new error message is presented to the user for each error found—or it can be batched, where all errors are presented as a single message. There are other dimensions to validation and error processing, such as the degree of error that is tolerated and the experience level of the user. However, considering only the basic processes, the choice of when to error-check and when to notify the user, leads to four common approaches:
- Interactive validation with field-by-field errors. The data in each field is validated when the user exits or changes the field. If there is an error, the user is alerted to that error and may be required to fix the error before proceeding.
- Interactive validation with batched errors. The data in all fields is validated when the user leaves one field. If there are one or more errors, the user is alerted to these, and can't proceed beyond the current page without fixing all errors.
- Post-validation with field-by-field errors. The user first enters all data with no validation. The data is then checked and errors are reported for each field, one by one. The user fixes each error in turn and resubmits the data for revalidation.
- Post-validation with batched errors. The user first enters all data with no validation. The data is then checked, and all errors in the data are reported in one message to the user. The user then fixes all errors and resubmits the data for revalidation.
Contents |
Examples
Check if a form data value is an integer
if ($_POST['age'] != strval( intval($_POST['age'])){
$errors['invalidAge'] = 'Invalid value for age';
}
Check if a form data value is not empty
if ($params['myName'] ==''){
$errors['myName'] = 'Name must not be empty';
}
Check if a form data value is alphabetic
if (!(ereg("^[a-z]*$", $params['myName']))){
$errors['myName'] = 'Name must be alphabetic';
}
Validating an email address
$validEmail = "^[0-9a-z~!#$%&_-]([.]?[0-9a-z~!#$%&_-])*"."@[0-9a-z~!#$%&_-]([.]?[0-9a-z~!#$%&_-])*$";
if (!eregi($validEmail, $email)){
$errors['invalidEmail'] = 'Please enter a valid email!';
}

