“Focus 90% of your time on solutions
and only 10% of your time on problems.”

PHP 5 Form Validation class

Posted by Alessandro on Mar 17, 2013 12:23:18 PM
Filed under PHP | Comments (2)

Average: 0/100 (0 ratings)

QR Code

I'm here today for introducing you the new version of my PHP Form Validation Class.

Just another validation class? Maybe. But I've been using it for many years when I don't use other frameworks to develop my applications. And I find it really useful and easy to use. So today I want to share it with you as it could be useful to you too.

So I've decided to release it licensed as GPL to allow you to use it for free and also change it to best fit your own needs.

So, first I'm giving you the source code, then I'll show you some practical examples for implementing it into your code and some suggestions for using it at its top.

First of all, what are its stronger features? Well, it can easily validate your html form simply by passing your data to validate and a validation map as arrays.

Then you can pass another array with a translation map, so it can be easily localized amd error messages are translated into your desired language.

Another feature is made by the static validators, that can be used to validate data without creating any class instance. And, subclassing it, you can easily overwrite my validators with your own.

So, let's see some code.

Code:

  1. <?php
  2. /**
  3. * Class FormValidate
  4. *
  5. * Form Validation class
  6. * This new version includes many new features and a completed re-engeneering in PHP 5
  7. *
  8. * @category FormValidation
  9. * @package IWEPhpFramework
  10. * @author Alessandro Perrone <info@iweconsulting.net>
  11. * @copyright 2008-2013 IWE Consulting
  12. * @license http://opensource.org/licenses/GPL-3.0 GNU General Public License, version 3 (GPL-3.0)
  13. * @version 1.4
  14. *
  15. */
  16. class FormValidate {
  17. /**
  18. * Translations array
  19. * @access protected
  20. * @var array
  21. */
  22. protected $translations = array();
  23. /**
  24. * Translations array
  25. * @access protected
  26. * @var array
  27. */
  28. protected $error_messages = array();
  29. /**
  30. * Email confirmation
  31. * @access protected
  32. * @var string
  33. */
  34. protected static $confirm_email = NULL;
  35. /**
  36. * Password confirmation (if the form treats this kind of information)
  37. * @access protected
  38. * @var string
  39. */
  40. protected static $confirm_password = NULL;
  41. /**
  42. * Recaptcha private key
  43. * @access protected
  44. * @var string
  45. */
  46. protected static $recaptcha_pkey = NULL;
  47. /**
  48. * Data associative array (contains data to validate)
  49. * @access protected
  50. * @var array (associative)
  51. */
  52. protected $data;
  53. /**
  54. * E-mail check switch
  55. * @access protected
  56. * @var boolean
  57. */
  58. protected static $email_processed = false;
  59. /**
  60. * Password check switch
  61. * @access protected
  62. * @var boolean
  63. */
  64. protected static $password_processed = false;
  65. /**
  66. * Validation schema
  67. * @access protected
  68. * @var array (multidimensional)
  69. */
  70. protected $validator;
  71. /**
  72. * Password fields minimum lenght
  73. * @access public
  74. * @var int
  75. */
  76. public static $password_min_lenght = 8;
  77. /**
  78. * Static Errors
  79. * @access public
  80. * @var boolean
  81. */
  82. public static $errors = false;
  83. /**
  84. * Static Errors list
  85. * @access public
  86. * @var array
  87. */
  88. public static $errors_list = array();
  89. /**
  90. * Static Validation success
  91. * @access public
  92. * @var boolean
  93. */
  94. public static $success = false;
  95. /**
  96. * Static Warnings
  97. * @access public
  98. * @var unknown
  99. */
  100. public static $warnings = false;
  101. /**
  102. * Static Warnings list
  103. * @access public
  104. * @var unknown
  105. */
  106. public static $warnings_list = array();
  107. /**
  108. * FormValidate constructor
  109. * @param array $validation_array (multidimensional with validation schema)
  110. * @param array $data (ssociative with data to be validated)
  111. * @access public
  112. */
  113. public function __construct(Array $validation_array, Array $data, Array $translations = array()){
  114. /*
  115. foreach($validation_array as $key => $value) echo "$key: $value<br />\n";
  116. echo "---------------------<br />";
  117. foreach($data as $key => $value) echo "$key: $value<br />\n";
  118. */
  119. $this->confirm_email = NULL;
  120. $this->confirm_password = NULL;
  121. $this->email_processed = false;
  122. $this->password_processed = false;
  123. $this->data = $data;
  124. $this->validator = $validation_array;
  125. $this->initErrorMessages();
  126. $this->setTranslations($translations);
  127. }
  128. /**
  129. * Initialize error messages array
  130. * @access private
  131. */
  132. final private function initErrorMessages()
  133. {
  134. $this->error_messages = array(
  135. 'FIELD_PRIVACY' => '',
  136. 'FIELD_LENGHT' => '',
  137. 'FIELD_MAX_LENGHT' => '',
  138. 'FIELD_MIN_LENGHT' => '',
  139. 'FIELD_REQUIRED' => '',
  140. 'FIELD_TYPE_STRING' => '',
  141. 'FIELD_TYPE_NUMBER' => '',
  142. 'FIELD_TYPE_MONEY' => '',
  143. 'FIELD_TYPE_TELEPHONE' => '',
  144. 'FIELD_TYPE_CONFIRM_PASSWORD' => '',
  145. 'FIELD_TYPE_SIMPLE_PASSWORD' => '',
  146. 'FIELD_TYPE_ALPHANUMERIC' => '',
  147. 'FIELD_TYPE_PASSWORD' => '',
  148. 'FIELD_TYPE_PASSWORD_HINT' => '',
  149. 'FIELD_TYPE_EMAIL' => '',
  150. 'FIELD_TYPE_CONFIRM_EMAIL' => '',
  151. 'FIELD_TYPE_TEXT' => '',
  152. 'FIELD_TYPE_DATE' => '',
  153. 'FIELD_TYPE_CAPTCHA' => '',
  154. 'FIELD_TYPE_RECAPTCHA' => '',
  155. );
  156. }
  157. /**
  158. * Setup error messages translations.
  159. * This can be done in two ways: passing an array with translated messages (only specified keys will be
  160. * translated) as argument for this method or, if subclassing, overwriting this method and setting up
  161. * a new translations array in the class $translations member
  162. * @access protected
  163. * @param array $translations
  164. */
  165. protected function setTranslations(Array $translations = array())
  166. {
  167. $this->translations = array(
  168. 'FIELD_PRIVACY' => "You must agree with the privacy agreement.",
  169. 'FIELD_LENGHT' => "Field <em>'%s'</em> should be %s chars long.",
  170. 'FIELD_MAX_LENGHT' => "Field <em>'%s'</em> could contain only %s chars.",
  171. 'FIELD_MIN_LENGHT' => "Field <em>'%s'</em> could contain only %s chars.",
  172. 'FIELD_REQUIRED' => "Field <em>'%s'</em> is required.",
  173. 'FIELD_TYPE_STRING' => "Field <em>'%s'</em> should be a string.",
  174. 'FIELD_TYPE_NUMBER' => "Field <em>'%s'</em> should be a number.",
  175. 'FIELD_TYPE_MONEY' => "Field <em>'%s'</em> is not a valid money data.",
  176. 'FIELD_TYPE_TELEPHONE' => "Field <em>'%s'</em> is not a valid telephone number.",
  177. 'FIELD_TYPE_CONFIRM_PASSWORD' => "Check password is different from password.",
  178. 'FIELD_TYPE_SIMPLE_PASSWORD' => "Field <em>'%s'</em> is too short (must be " . self::$password_min_lenght . " chars long).",
  179. 'FIELD_TYPE_ALPHANUMERIC' => "Field <em>'%s'</em> should be alphanumeric.",
  180. 'FIELD_TYPE_PASSWORD' => "Field <em>'%s'</em> is not a valida password.",
  181. 'FIELD_TYPE_PASSWORD_HINT' => "Field <em>'%s'</em> may contain special chars to increase security (i.e. \"passWord.25\")",
  182. 'FIELD_TYPE_EMAIL' => "Field <em>'%s'</em> is not a valid e-mail.",
  183. 'FIELD_TYPE_CONFIRM_EMAIL' => "Check e-mail is different from e-mail.",
  184. 'FIELD_TYPE_TEXT' => "Field <em>'%s'</em> should contain more information.",
  185. 'FIELD_TYPE_DATE' => "Field <em>'%s'</em> is not a valid date: valid format is mm-gg-aaaa.",
  186. 'FIELD_TYPE_CAPTCHA' => "Captcha text is not valid!",
  187. 'FIELD_TYPE_RECAPTCHA' => "Invalid Recaptcha!",
  188. );
  189. if(!empty($translations)){
  190. foreach($translations as $key => $value){
  191. if(array_key_exists($key, $this->translations)){
  192. $this->translations[$key] = $value;
  193. }
  194. }
  195. }
  196. $this->setErrorMessages();
  197. }
  198. /**
  199. * Create object of error messages to use as validation output
  200. * @access private
  201. */
  202. final private function setErrorMessages()
  203. {
  204. $tmp = array();
  205. foreach($this->translations as $key => $value){
  206. if(array_key_exists($key, $this->error_messages) && !empty($value)){
  207. $tmp[strtolower($key)] = $value;
  208. }else{
  209. $tmp[strtolower($key)] = $this->error_messages[$key];
  210. }
  211. }
  212. $this->error_messages = $tmp;
  213. unset($tmp);
  214. $this->error_messages = $this->__toObject($this->error_messages);
  215. }
  216. /**
  217. * validate method
  218. * execute data validation for each data of the $data array parsing each time the relative validation schema
  219. * @param array $validation_array (multidimensional with validation schema)
  220. * @param array $data (associative with data to be validated)
  221. * @access public
  222. * @return array/boolean
  223. */
  224. public function validate(){
  225. ## INIT VARIABLES
  226. $errors = $warnings = array();
  227. $return = array();
  228. ## CREATE VALIDATION MAP
  229. $data_to_validate = array();
  230. foreach($this->validator as $key => $value){
  231. //if(!in_array(strtolower($key), $this->data))
  232. $key = strtolower($key);
  233. if(!array_key_exists($key, $this->data))
  234. return false;
  235. else
  236. $data_to_validate[$key] = $this->data[$key];
  237. }
  238. ## EXECUTE VALIDATION ON MAPPED POST DATA
  239. //if(count($this->validator) == count($this->data)){
  240. //foreach($this->data as $key=>$value){
  241. foreach($data_to_validate as $key => $value){
  242. //echo $this->validator[$key] . "<br />";
  243. $validate = $this->check_data($key, $value, $this->validator[$key]);
  244. if(count($validate) > 0){
  245. if(array_key_exists('error_description', $validate)){
  246. self::$errors = true;
  247. $errors[] = array('field' => $key, 'message' => $validate['error_description']);
  248. }
  249. if(array_key_exists('warning', $validate)){
  250. self::$warnings = true;
  251. $warnings[] = array('field' => $key, 'message' => $validate['warning']);
  252. }
  253. }
  254. }
  255. ## IF AN ERROR OCCURS RETURN FALSE
  256. if(!empty($errors) && !empty($warnings)){
  257. $return['success'] = false;
  258. $return['errors'] = self::$errors_list = array_merge($errors, $warnings);
  259. return $return;
  260. }elseif(!empty($errors)){
  261. $return['success'] = false;
  262. $return['errors'] = self::$errors_list = $errors;
  263. return $return;
  264. ## IF A WARNING OCCURS RETURN TRUE GIVING THE DEVELOPER CHOICE TO GIVE USER A SECOND CHANCE
  265. }elseif(!empty($warnings)){
  266. $return['success'] = self::$success = true;
  267. $return['warnings'] = self::$warnings_list = $warnings;
  268. return $return;
  269. ## IF ALL IS OK RETURN TRUE
  270. }else
  271. return true;
  272. /*
  273. }else
  274. return false;
  275. */
  276. }
  277. /**
  278. * check_data method
  279. * execute data validation for the data passed referring to the data validation schema.
  280. * @param string $field (name of the current field/variable to be parsed)
  281. * @param mixed $data (data to be checked)
  282. * @param array $check_table (validation schema)
  283. * @access private
  284. * @return array
  285. */
  286. protected function check_data($field, $data, $check_table){
  287. ## INIT VARIABLES
  288. $error = $warning = "";
  289. $return = array();
  290. $lenght = array_key_exists('lenght', $check_table) ? $check_table['lenght'] : false;
  291. $minlenght = array_key_exists('minlenght', $check_table) ? $check_table['minlenght'] : false;
  292. $maxlenght = array_key_exists('maxlenght', $check_table) ? $check_table['maxlenght'] : false;
  293. $required = array_key_exists('required', $check_table) ? $check_table['required'] : false;
  294. $type = array_key_exists('type', $check_table) ? $check_table['type'] : false;
  295. self::$recaptcha_pkey = array_key_exists('recaptcha_pk', $check_table) ? $check_table['recaptcha_pk'] : false;
  296. ## IF THE FIELD IS REQUIRED CHECK IF EMPTY AND RETURN AN ERROR
  297. if($required){
  298. if(empty($data)){
  299. $error .= ($field == "privacy") || ($field == "consenso_privacy") ? $this->error_messages->field_privacy : sprintf($this->error_messages->field_required, ucfirst($field));
  300. //$return['error_description'] = nl2br($error);
  301. $return['error_description'] = $error;
  302. return $return;
  303. }
  304. }
  305. ## IF THE FIELD IS REQUIRED AND CONTAINS DATA OR IS OPTIONAL AND CONTAINS DATA EXECUTE LENGHT AND DATATYPE CHECKS
  306. # OR DO NOTHING IF IT'S A VOID (NULL) OPTIONAL FIELD
  307. if(!empty($data) && $data != "-"){
  308. ## TRIM SPACES
  309. $data = trim($data);
  310. ## EVALUATE LENGHT IF REQUIRED
  311. if(!empty($lenght)){
  312. if(strlen($data) < $lenght) $error .= sprintf($this->error_messages->field_lenght, ucfirst($field), $lenght);
  313. }
  314. if(!empty($minlenght)){
  315. if(strlen($data) < $minlenght) $error .= sprintf($this->error_messages->field_minlenght, ucfirst($field), $minlenght);
  316. }
  317. if(!empty($maxlenght)){
  318. if(strlen($data) > $maxlenght) $error .= sprintf($this->error_messages->field_maxlenght, ucfirst($field), $maxlenght);
  319. }
  320. ## DATATYPE VALIDATION
  321. switch($type){
  322. case 'string':
  323. $validation = $this->validateString($data);
  324. if($validation === false){
  325. $error .= sprintf($this->error_messages->field_lenght, ucfirst($field));
  326. }else if($validation === -1){
  327. $error .= sprintf($this->error_messages->field_required, ucfirst($field));
  328. }
  329. break;
  330. case 'int':
  331. case 'number':
  332. if(!$this->validateNumber($data))
  333. $error .= sprintf($this->error_messages->field_type_number, ucfirst($field));
  334. break;
  335. case 'money':
  336. if(!$this->validateMoney($data))
  337. $error .= sprintf($this->error_messages->field_type_money, ucfirst($field));
  338. break;
  339. case 'telephone':
  340. if(!$this->validateTelephone($data))
  341. $error .= sprintf($this->error_messages->field_type_telephone, ucfirst($field));
  342. break;
  343. case 'confirm_password':
  344. if(!$this->validateConfirmPassword($data))
  345. $error .= $this->error_messages->field_type_confirm_password;
  346. break;
  347. case 'simple_password':
  348. if(!$this->validateSimplePassword($data))
  349. $error .= sprintf($this->error_messages->field_type_simple_password, ucfirst($field));
  350. break;
  351. case 'password':
  352. $validation = $this->validatePassword($data);
  353. if($validation === false){
  354. $error .= sprintf($this->error_messages->field_type_simple_password, ucfirst($field));
  355. }else if($validation === -1){
  356. $warning .= sprintf($this->error_messages->field_type_password_hint, ucfirst($field));
  357. }else if($validation === -2){
  358. $error .= sprintf($this->error_messages->field_type_alphanumeric, ucfirst($field));
  359. }
  360. break;
  361. case 'email':
  362. if(!$this->validateEmail($data))
  363. $error .= sprintf($this->error_messages->field_type_email, ucfirst($field));
  364. break;
  365. case 'confirm_email':
  366. if(!$this->validateConfirmEmail($data))
  367. $error .= $this->error_messages->field_type_confirm_email;
  368. break;
  369. case 'text':
  370. if(!$this->validateText($data))
  371. $error .= sprintf($this->error_messages->field_type_text, ucfirst($field));
  372. break;
  373. case 'date':
  374. if(!$this->validateDate($data))
  375. $error .= sprintf($this->error_messages->field_type_date, ucfirst($field));
  376. break;
  377. case 'checktext':
  378. if(!$this->validateCaptcha($data))
  379. $error .= $this->error_messages->field_type_captcha;
  380. break;
  381. case 'recaptcha':
  382. // remember to include recaptchalib on your main file!
  383. $validation = $this->validateRecaptcha($data);
  384. if($validation === false){
  385. $error .= $this->error_messages->field_type_recaptcha;
  386. }else if($validation !== true){
  387. $error .= $validation;
  388. }
  389. break;
  390. case 'privacy':
  391. if(!$this->validatePrivacy($data))
  392. $error .= $this->error_messages->field_type_privacy;
  393. break;
  394. case NULL:
  395. $error .= NULL;
  396. $warning .= NULL;
  397. break;
  398. }
  399. }
  400. ## FILL RETURN DATA IF ERRORS OR WARNINGS OCCURED
  401. if(!empty($warning)){
  402. $return['warning'] = nl2br($warning);
  403. }
  404. if(!empty($error)){
  405. $return['error_description'] = nl2br($error);
  406. }
  407. ## RETURN VALIDATED DATA
  408. return $return;
  409. }
  410. /**
  411. * Validate String
  412. * @param string $string
  413. * @return Ambigous <boolean, number>
  414. * @access public
  415. */
  416. public static function validateString($string = null)
  417. {
  418. $return = false;
  419. if(is_string($string) || strstr($string, "...") === false)
  420. $return = true;
  421. else if(strstr($string, "...") !== false)
  422. $return = -1;
  423. return $return;
  424. }
  425. /**
  426. * Validate Privacy
  427. * @param string $privacy
  428. * @return boolean
  429. * @access public
  430. */
  431. public static function validatePrivacy($privacy = null)
  432. {
  433. $return = false;
  434. if(intval($privacy) == 1){
  435. $return = true;
  436. }
  437. return $return;
  438. }
  439. /**
  440. * Validate Numeric field
  441. * @param string $number
  442. * @return boolean
  443. * @access public
  444. */
  445. public static function validateNumber($number = null)
  446. {
  447. $return = false;
  448. if(is_numeric($number)){
  449. $return = true;
  450. }
  451. return $return;
  452. }
  453. /**
  454. * Validate Email
  455. * @param string $email
  456. * @return boolean
  457. * @access public
  458. */
  459. public static function validateEmail($email = null)
  460. {
  461. $return = false;
  462. self::$email_processed = true;
  463. if(preg_match("/^([\w.-]+)@(([a-zA-Z0-9_-])+|([a-zA-Z0-9_-])+.([a-zA-Z0-9_-])+)\.(\w){2,4}$/", $email)){
  464. self::$confirm_email = $email;
  465. $return = true;
  466. }
  467. return $return;
  468. }
  469. /**
  470. * Validate Confirmation Email
  471. * @param string $email
  472. * @return boolean
  473. * @access public
  474. */
  475. public static function validateConfirmEmail($email = null)
  476. {
  477. $return = false;
  478. if(self::$email_processed && !empty(self::$confirm_email)){
  479. if($email == self::$confirm_email){
  480. $return = true;
  481. }
  482. }
  483. return $return;
  484. }
  485. /**
  486. * Validate Simple Password
  487. * @param string $password
  488. * @return boolean
  489. * @access public
  490. */
  491. public static function validateSimplePassword($password = null)
  492. {
  493. $return = false;
  494. self::$password_processed = true;
  495. if(preg_match("/^(.){" . self::$password_min_lenght . ",}$/", $password)){
  496. self::$confirm_password = $password;
  497. $return = true;
  498. }
  499. return $return;
  500. }
  501. /**
  502. * Validate Password
  503. * @param string $password
  504. * @return Ambigous <boolean, number>
  505. * @access public
  506. */
  507. public static function validatePassword($password = null)
  508. {
  509. $return = false;
  510. self::$password_processed = true;
  511. if(preg_match("/^(.){" . self::$password_min_lenght . ",}$/", $password)){
  512. if(!preg_match("/^(\D)+$/", $password)){
  513. self::$confirm_password = $password;
  514. if(preg_match("/[\/\^!?\"'[\]+\-.:,;()|\\]+/", $password)){
  515. $return = true;
  516. }else{
  517. $return = -1;
  518. }
  519. }else{
  520. $return = -2;
  521. }
  522. }
  523. return $return;
  524. }
  525. /**
  526. * Validate Confirmation Password
  527. * @param string $password
  528. * @return boolean
  529. * @access public
  530. */
  531. public static function validateConfirmPassword($password = null)
  532. {
  533. $return = false;
  534. if(self::$password_processed && !empty(self::$confirm_password)){
  535. if($password == self::$confirm_password){
  536. $return = true;
  537. }
  538. }
  539. return $return;
  540. }
  541. /**
  542. * Validate Money data type
  543. * @param string $money
  544. * @return boolean
  545. * @access public
  546. */
  547. public static function validateMoney($money = null)
  548. {
  549. $return = false;
  550. if(preg_match('/^([\d]+)(\.|,)([\d]{2})$/', $money)){
  551. $return = true;
  552. }
  553. return $return;
  554. }
  555. /**
  556. * Validate Telephone number
  557. * @param string $telephone
  558. * @return boolean
  559. * @access public
  560. */
  561. public static function validateTelephone($telephone = null)
  562. {
  563. $return = false;
  564. if(preg_match("/^(\+\d\d)?[\s.\-\/]?([0]?[1-9]{1,3})[\s.\-\/]?([0-9]{4,8})$/", $telephone)){
  565. $return = true;
  566. }
  567. return $return;
  568. }
  569. /**
  570. * Validate Text field (long text)
  571. * @param string $text
  572. * @return boolean
  573. * @access public
  574. */
  575. public static function validateText($text = null)
  576. {
  577. $return = false;
  578. if(is_string($text) && strlen($text) >= 10){
  579. $return = true;
  580. }
  581. return $return;
  582. }
  583. /**
  584. * Validate Date data type
  585. * @param string $date
  586. * @return boolean
  587. * @access public
  588. */
  589. public static function validateDate($date = null)
  590. {
  591. $return = false;
  592. if(preg_match("/^(0?[1-9]|1[012])[\-.\/](0?[1-9]|[12][0-9]|3[01])[\-.\/]((19|20)\d\d)$/", $date)){
  593. $return = true;
  594. }
  595. return $return;
  596. }
  597. /**
  598. * Validate Captcha string
  599. * @param string $string
  600. * @return boolean
  601. * @access public
  602. */
  603. public static function validateCaptcha($string = null)
  604. {
  605. $return = false;
  606. session_start();
  607. if(strtolower($string) == strtolower($_SESSION['randomStr'])){
  608. $return = true;
  609. }
  610. return $return;
  611. }
  612. /**
  613. * Validate Recaptcha field
  614. * @param string $string
  615. * @return boolean
  616. * @access public
  617. */
  618. public static function validateRecaptcha($string = null)
  619. {
  620. // remember to include recaptchalib on your main file!
  621. $return = false;
  622. if(!empty(self::$recaptcha_pkey)){
  623. $fields = preg_split("/\[\]/", $string);
  624. $resp = recaptcha_check_answer(self::$recaptcha_pkey,
  625. $_SERVER["REMOTE_ADDR"],
  626. $fields[1],
  627. $fields[0]);
  628. if($resp->is_valid){
  629. $return = true;
  630. }else{
  631. $return = $resp->error;
  632. }
  633. }
  634. return $return;
  635. }
  636. /**
  637. * Return an array as object notation
  638. * @return Object
  639. * @access private
  640. */
  641. final private function __toObject(Array $array)
  642. {
  643. $obj = new stdClass;
  644. foreach($array as $k => $v){
  645. if(is_array($v)){
  646. $obj->{$k} = $this->__toObject($v); //RECURSION
  647. }else{
  648. $obj->{$k} = $v;
  649. }
  650. }
  651. return $obj;
  652. }
  653. }

You can download the class file and see its code here.

Ok, that's the class. And what now? How to use it? As I told you before, you have to create your html form, then you must create two arrays, one for the data to validate and one with a validation map that the class has to follow to complete validation.

Pay attention to your form inputs, they must contain an id attribute to match the validation key map.

Here's a basic validation example:

Code:

  1. <?php
  2. if(!empty($_POST)){
  3. $data = array(
  4. 'name' => $_POST['name'],
  5. 'surname' => $_POST['surname'],
  6. 'phone' => $_POST['phone'],
  7. 'email' => $_POST['email'],
  8. 'email_confirmation' => $_POST['email_confirmation'],
  9. 'password' => $_POST['password'],
  10. 'password_confirmation' => $_POST['password_confirmation'],
  11. 'address' => $_POST['address'],
  12. 'city' => $_POST['city'],
  13. 'birth_date' => $_POST['birthdate']['month'].'-'.$_POST['birthdate']['day'].'-'.$_POST['birthdate']['year'],
  14. );
  15. $validation_key = array(
  16. 'name' => array('required' => true, 'type' => 'string'),
  17. 'surname' => array('required' => true, 'type' => 'string'),
  18. 'phone' => array('required' => true, 'type' => 'telephone'),
  19. 'email' => array('required' => true, 'type' => 'email'),
  20. 'email_confirmation' => array('required' => true, 'type' => 'confirm_email'),
  21. 'password' => array('required' => true, 'type' => 'password'),
  22. 'password_confirmation' => array('required' => true, 'type' => 'confirm_password'),
  23. 'address' => array('required' => true, 'type' => 'string'),
  24. 'city' => array('required' => true, 'type' => 'string'),
  25. 'birth_date' => array('required' => false, 'type' => 'date'),
  26. );
  27. $validator = new FormValidate($validation_key, $data);
  28. if($validator === true){
  29. // SEND FORM DATA OR PERFORM OTHER ACTIONS
  30. }else{
  31. // VALIDATION ERRORS
  32. }
  33. }else{
  34. // SHOW HTML FORM
  35. }

As you can see, the class return true on a totally valid form, else it returns an array, containing a success key and errors and/or warnings keys: if there are errors the success is false, if there are warnings the success is true and you will decide what to do with you form.

You can also checking for errors and warnings with the public class members $errors and $warnings and access error and warning messages statically using the class members $warnings_list and $errors_list. Obviously you have to do this only after calling the validate() method.

You can manage validation also from Ajax forms, you only have to remember to pass your data with the right keys names. Here's an example using JQuery:

Code:

  1. $('#your_form').submit(function(e){
  2. e.preventDefault();
  3. // gather fields data
  4. data = {
  5. name: $('#name').val(),
  6. surname: $('#surname').val(),
  7. phone: $('#phone').val(),
  8. email: $('#email').val(),
  9. email_confirmation: $('#email_confirmation').val(),
  10. password: $('#password').val(),
  11. password_confirmation: $('#password_confirmation').val(),
  12. address: $('#address').val(),
  13. city: $('#city').val(),
  14. birthdate: {day: $('#birthdate_day').val(), month: $('#birthdate_month').val(), year: $('#birthdate_year').val()},
  15. };
  16. $.ajax({
  17. type: 'POST',
  18. dataType: 'json',
  19. url: $(this).attr('action') + '/validate',
  20. data: data,
  21. success: function(json){
  22. var success = json === true ? json : json.success;
  23. if(!success){
  24. var errors = json.errors;
  25. console.log(errors);
  26. }else{
  27. var warnings = json.warnings;
  28. if(typeof warnings !== 'undefined'){
  29. console.log(warnings);
  30. }else{
  31. // send form
  32. }
  33. }
  34. }
  35. });
  36. });

Another cool feature is the translation/customization of error message. You can setup your own error messages creating an associative array that must match the internal translation keys and passing it to the constructor:

Code:

  1. <?php
  2. $translations = array(
  3. 'FIELD_PRIVACY' => 'Your translation',
  4. 'FIELD_LENGHT' => 'Your translation',
  5. 'FIELD_MAX_LENGHT' => 'Your translation',
  6. 'FIELD_MIN_LENGHT' => 'Your translation',
  7. 'FIELD_REQUIRED' => 'Your translation',
  8. 'FIELD_TYPE_STRING' => 'Your translation',
  9. 'FIELD_TYPE_NUMBER' => 'Your translation',
  10. 'FIELD_TYPE_MONEY' => 'Your translation',
  11. 'FIELD_TYPE_TELEPHONE' => 'Your translation',
  12. 'FIELD_TYPE_CONFIRM_PASSWORD' => 'Your translation',
  13. 'FIELD_TYPE_SIMPLE_PASSWORD' => 'Your translation',
  14. 'FIELD_TYPE_ALPHANUMERIC' => 'Your translation',
  15. 'FIELD_TYPE_PASSWORD' => 'Your translation',
  16. 'FIELD_TYPE_PASSWORD_HINT' => 'Your translation',
  17. 'FIELD_TYPE_EMAIL' => 'Your translation',
  18. 'FIELD_TYPE_CONFIRM_EMAIL' => 'Your translation',
  19. 'FIELD_TYPE_TEXT' => 'Your translation',
  20. 'FIELD_TYPE_DATE' => 'Your translation',
  21. 'FIELD_TYPE_CAPTCHA' => 'Your translation',
  22. 'FIELD_TYPE_RECAPTCHA' => 'Your translation',
  23. );
  24. $validator = new FormValidate($validation_key, $data, $translations);

You can only overwrite the values you need as well, without customizing all the translation keys.

Please, make sure to keep variables where required (take a look at the internal translation for this). For example, for field lenght you will find an error message like "Field '%s' should be %s chars long."

You can find a working example of this class at http://examples.iweconsulting.net/formvalidate/.

I hope this class can be useful to you. Please, leave feedbacks! Thanks.

Back to top

2 comments

Alessandro | Mar 25, 2013 5:23:54 PM

The working example is now at your disposal, I\'m sorry if someone wasn\'t able to access it before.

Alessandro | Mar 21, 2013 10:59:29 AM

Line 295 is now correct. In previous code it contained a wrong reference to the static variable $recaptcha_pkey ($this was used in place of self).

<< | < Previous | 1 | Next > | >>

Records 1 - 2 of 2 total

Login or register to add a comment (registered users only)

Back to top

Site search
Are you a member?

Lost your password?

Register

Website Authentication

Posted by Alessandro on Nov 20, 2012 5:45:38 PM
Filed under Security | Comments (0)

Today I've discovered a really huge security issue in some websites I was working on (made by some not "security oriented" developers, or maybe not experienced in this kind of subject). They were made in PHP, but the issue is a logical one […]

Read more

Microsoft Windows 8

Posted by Alessandro on Nov 14, 2012 10:54:59 AM
Filed under generic | Comments (0)

Microsoft Windows 8 è "finalmente" arrivato ed io, nonostante non mi sia mai appassionato tanto ai sistemi operativi, né abbia in particolare una qualche simpatia verso la Microsoft sono stato preso da un "raptus" di[…]

Read more

SETTING UP A PROXY SERVER WITH FIDDLER2 ON YOUR LAN

Posted by Alessandro on Nov 1, 2012 4:25:20 AM
Filed under Networking | Comments (0)

Yesterday I was playing a little around with that wonderful piece of software for Windows called Fiddler2. Fiddler2 is technically a proxy but it has got tons of web debugging features, so it's also used for security testing on websites. But today[…]

Read more

Playing around with Magento Newsletter

Posted by Alessandro on Oct 12, 2012 10:43:50 AM
Filed under Magento | Comments (0)

One of the most useful Magento features (I'm writing about Magento Community) is its Newsletter: it can manage well formed newsletter documents and, most important, it can send them for free, so you can forget about commercial services like Infomail,[…]

Read more

Zend Server Community 5.6 does not start Apache on Windows

Posted by Alessandro on Jul 7, 2012 10:17:46 AM
Filed under PHP | Comments (0)

Yesterday I decided to upgrade my development machine Zend Server Community version as the installed version was a little old and I wanted to have a more up to date server. I love Zend Server, especially on Windows, as it gives me all the tools I ne[…]

Read more

Paypal Donate Button