Es muy recomendable validar cualquier tipo de dato que entre dentro de nuestros algoritmos. Ya sea para hacerlo más robusto a fallos de rendimiento, de errores o de hackeos. Una de las formas más extendida d validar datos es con expresiones regulares, ya que son muy versatiles.
La clase PHP es muy sencilla y únicamente se encarga de validar un string con una expresión regular a medida para ese tipo de dato. Ya sea un email, un texto largo, o un número de teléfono.
<?php
class Validator {
private $regExpChars = array(
"names" => array(
"description" => "Letters, digits, dots, hyphens, white spaces, 1 min length and 255 max length",
"regExp" => '/^[\p{L}\ \dÀ-ÿ]{1,255}$/i'
),
"telephone" => array(
"description" => "Digits, plus, parenthesis and withe spaces, example formats: +000000000000 | +00 00 00000-0000 | +000 0 000-0000 | (+00) 0000 0000 000",
"regExp" => '/^\(?\+[0-9]{1,3}\)? ?-?[0-9]{1,3} ?-?[0-9]{3,5} ?-?[0-9]{4}( ?-?[0-9]{3})? ?(\w{1,10}\s?\d{1,6})$/'
),
"large_text" => array(
"description" => "Digits, letters, accents, hyphens, dots, double dots, comma, dot and comma, tab, return, white spaces, 1 of min length and 2000 chars max length.",
"regExp" => '/^[\p{L}\ \d\_\-\.\,\;\:\t\nÀ-ÿ]{1,2000}$/i'
),
"recaptcha" => array(
"description" => "English letters and middle hyphen.",
"regExp" => '/^[\w-]*$/'
),
"email" => array(
"description" => "Email format is required.",
"regExp" => '/^(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){255,})(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){65,}@)(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22))(?:\.(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\]))$/iD'
)
);
public function isValid( $nameRegExp, $stringToVal ){
if( !preg_match($this->regExpChars[$nameRegExp]["regExp"], $stringToVal ) ){
return $this->regExpChars[$nameRegExp]["description"];
}
return false;
}
}
Parar usarla simplemente instanciamos el objecto y llamamos a la función isValid.
<?php
$validator = new Validator();
$validator->isValid("email","pepe@pepe.com");
?>
En caso de ser valido nos devolverá True y sino nos devolverá False.