First, don't use ereg*()
functions for regular expressions matching, these are deprecated and slow. Use the preg_*()
functions instead.
Also take a look at PHP's filter extension.
It provides functions to check and validate various data which you can use directly or incorporate into your own validator functions.
EDIT: Example for checking an e-mail address (see also examples on php.net):
if ( !filter_var($email, FILTER_VALIDATE_EMAIL) ) {
echo 'Invalid e-mail "'.$email.'"';
Speaking of validation in an object-oriented manner, you could have a generic validator class with basic validation functions (where you could also integrate filter
functions for a consistent API).
Additionally, if your data logically belongs together such that you can group them into objects and manage them as such, implement a validate()
method in the classes of these objects that checks the object's properties by utilizing the filter
functions and/or your validator class.
class Message {
private $name;
private $email;
private $text;
...
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getEMail() {
return $this->email;
}
public function setEMail($email) {
$this->email = $email;
}
...
public function validate() {
$errors = array();
$nameLength = strlen($this->name);
if ( ($nameLength === 0) or ($nameLength > self::NAME_MAX_LENGTH) )
$errors['name'] = 'Name must be between 1 and '.self::NAME_MAX_LENGTH.' characters.';
if ( !Validator::isEMail($this->email) )
$errors['email'] = 'Invalid e-mail "'.$this->email.'"';
// Other checks
...
// Return TRUE if successful, otherwise array of errors
return ( count($errors) === 0 ? true : $errors );
}
}
Then, you could load all your form inputs into your object like this:
$message = new Message();
$message->setName($_POST['name']);
$message->setEMail($_POST['email']);
$message->setText($_POST['text']);
...
$result = $message->validate();
if ( $result === true ) {
// Success
} else {
// Error
foreach ($result as $validationError) {
// Print error
echo htmlentities($validationError).'<br />';
}
}