“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 (4)

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

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

4 comments

Alessandro | Nov 26, 2013 4:15:07 PM

As reported by user Giuperry (thanks a lot!), lines 315 and 318 contain an incorrect reference to the array indexes \'field_minlenght\' and \'field_maxlenght\' for the error_messages array. Correct values should be instead \'field_min_lenght\' and \'field_max_lenght\' to reflect the indexes declared in the original array processed by the class. if(!empty($minlenght)){ if(strlen($data) < $minlenght) $error .= sprintf($this->error_messages->field_min_lenght, ucfirst($field), $minlenght); } if(!empty($maxlenght)){ if(strlen($data) > $maxlenght) $error .= sprintf($this->error_messages->field_max_lenght, ucfirst($field), $maxlenght); }

Alessandro | Nov 26, 2013 4:14:25 PM

As reported by user Giuperry (thanks a lot!), lines 315 and 318 contain an incorrect reference to the array indexes \'field_minlenght\' and \'field_maxlenght\' for the error_messages array. Correct values should be instead \'field_min_lenght\' and \'field_max_lenght\' to reflect the indexes declared in the original array processed by the class. if(!empty($minlenght)){ if(strlen($data) < $minlenght) $error .= sprintf($this->error_messages->field_min_lenght, ucfirst($field), $minlenght); } if(!empty($maxlenght)){ if(strlen($data) > $maxlenght) $error .= sprintf($this->error_messages->field_max_lenght, ucfirst($field), $maxlenght); }

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 - 4 of 4 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