<?php
/**
* @author John Ciacia
* @copyright 2008
*/
class Validator
{
const ALPHA = 1;
const NUMBER = 2;
const ALPHNUM = 3;
const UPPER = 4;
const LOWER = 5;
function __construct()
{
}
//This function validates a string of a particular type.
//You can either pass in a number (1-5) or its defininion
//as defined above. If the string is of the valid type
//this function will return true. If the string is not
//of the valid type, it will return false.
static public function valid_string($input, $type)
{
switch ($type) {
//such a string can only contain alphabetical characters
case ALPHA:
if (preg_match('/^[a-z]+$/i', $input))
return true;
return false;
break;
//such a string can only contain numbers
case NUMBER:
if (preg_match('/^\d+$/', $input))
return true;
return false;
break;
//such a string can only contain numbers and alphabetical characters
case ALPHNUM:
if (preg_match('/^[a-zA-Z0-9]+$/i', $input))
return true;
return false;
break;
//such a string can only contain uppercase characters
case UPPER:
if (preg_match('/[A-Z]/', $input) && !preg_match('/[a-z]/', $input))
return true;
return false;
break;
//such a string can only contain lowercase characters
case LOWER:
if (!preg_match('/[A-Z]/', $input) && preg_match('/[a-z]/', $input))
return true;
return false;
break;
}
}
//This function checks whether an email address is valid. It is
//not perfect as it does not account for .museum email addresses
//however this tradeoff is preferable to the other downsides
//of allowing it.
static public function valid_email($input)
{
if (!eregi("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$", $input)) {
return false;
}
return true;
}
//This function checks whether a string is within certain size constraints.
//For example, the required length of a password might be 5 characters. Setting
//$min to 5 will require the password to be larger than or equal to five
//characters. If not, it will display an error message. If either $max
//or $min is set to 0, length checking is ignored on that constraing. The max
//constraint might be set on a contact form, where the text entered should
//not be any longer than 250 characters.
static public function valid_size($input, $min = 0, $max = 0)
{
//check the minimum size constraints
//in this case: the string needs to be longer
if (strlen($input) < $min) {
return false;
}
//check the maximum size constraints
//in this case: the string is too long
if (($max != 0) && (strlen($input) > $max)) {
return false;
}
return true;
}
}
?>
Don't understand regular expressions? This will get you started.
Edited by John, 03 September 2008 - 03:42 PM.


Sign In
Create Account

Back to top










