Home Backend Development PHP Tutorial php verification class

php verification class

Jul 25, 2016 am 09:12 AM

An extensible PHP verification class. Various verifications in the
class can be adjusted and implemented by themselves. This is the basic implementation method now.
If you need to add a rule, define the method directly, and the method name is the rule name. Please refer to the usage method for details.
  1. require_once('./Validator.class.php');
  2. $data = array(
  3. 'nickname' => 'heno' ,
  4. 'realname' => 'steven',
  5. 'age' = > 25,
  6. 'mobile' => '1521060426');
  7. $validator = new Validator($data);
  8. $validator->setRule('nickname', 'required');
  9. $validator- >setRule('realname', array('length' => array(1,6), 'required'));
  10. $validator->setRule('age', array('required', 'digit' ));
  11. $validator->setRule('mobile', array('mobile'));
  12. $result = $validator->validate();
  13. var_dump($result);
  14. var_dump($validator- >getResultInfo());
Copy code
  1. /**
  2. * Validator data validation class
  3. * @package library
  4. * @category library
  5. * @author Steven
  6. * @version 1.0
  7. */
  8. /**
  9. * Validator data validation class
  10. * @package library
  11. * @category library
  12. * @author Steven
  13. * @version 1.0
  14. */
  15. class Validator {
  16. /**
  17. * Data to be verified
  18. * @var array
  19. */
  20. private $_data;
  21. / **
  22. * Verification rules
  23. * @var array
  24. */
  25. private $_ruleList = null;
  26. /**
  27. * Verification result
  28. * @var bool
  29. */
  30. private $_result = null;
  31. /**
  32. * Verification data information
  33. * @var array
  34. */
  35. private $_resultInfo = array();
  36. /**
  37. * Constructor
  38. * @param array $data Data to be verified
  39. */
  40. public function __construct($data = null)
  41. {
  42. if ($data) {
  43. $this->_data = $data;
  44. }
  45. }
  46. /**
  47. * Set verification rules
  48. * @param string $var with verification item key
  49. * @param mixed $rule Verification rules
  50. * @return void
  51. */
  52. public function setRule($var, $rule)
  53. {
  54. $this->_ruleList[$var] = $rule;
  55. }
  56. /**
  57. * 检验数据
  58. * @param array $data
  59. * </li> <li> * $data = array('nickname' => 'heno' , 'realname' => 'steven', 'age' => 25);</li> <li> * $validator = new Validator($data);</li> <li> * $validator->setRule('nickname', 'required');</li> <li> * $validator->setRule('realname', array('lenght' => array(1,4), 'required'));</li> <li> * $validator->setRule('age', array('required', 'digit'));</li> <li> * $result = $validator->validate();</li> <li> * var_dump($validator->getResultInfo());</li> <li> *
  60. * @return bool
  61. */
  62. public function validate($ data = null)
  63. {
  64. $result = true;
  65. /* If no verification rules are set, return true directly */
  66. if ($this->_ruleList === null || !count($this-> _ruleList)) {
  67. return $result;
  68. }
  69. /* If the rules have been set, verify the rules one by one*/
  70. foreach ($this->_ruleList as $ruleKey => $ruleItem) {
  71. / * If the verification rule is a single rule*/
  72. if (!is_array($ruleItem)) {
  73. $ruleItem = trim($ruleItem);
  74. if (method_exists($this, $ruleItem)) {
  75. /* Verification data , save the verification result*/
  76. $tmpResult = $this->$ruleItem($ruleKey);
  77. if (!$tmpResult) {
  78. $this->_resultInfo[$ruleKey][$ruleItem] = $tmpResult;
  79. $result = false;
  80. }
  81. }
  82. continue;
  83. }
  84. /* There are multiple verification rules*/
  85. foreach ($ruleItem as $ruleItemKey => $rule) {
  86. if (!is_array($ rule)) {
  87. $rule = trim($rule);
  88. if (method_exists($this, $rule)) {
  89. /* Verify data, set result set*/
  90. $tmpResult = $this->$ rule($ruleKey);
  91. if (!$tmpResult) {
  92. $this->_resultInfo[$ruleKey][$rule] = $tmpResult;
  93. $result = false;
  94. }
  95. }
  96. } else {
  97. if ( method_exists($this, $ruleItemKey)) {
  98. /* Verify data, set result set*/
  99. $tmpResult = $this->$ruleItemKey($ruleKey, $rule);
  100. if (!$tmpResult) {
  101. $this->_resultInfo[$ruleKey][$ruleItemKey] = $tmpResult;
  102. $result = false;
  103. }
  104. }
  105. }
  106. }
  107. }
  108. return $result;
  109. }
  110. /**
  111. * Get verification result data
  112. * @return [type] [description]
  113. */
  114. public function getResultInfo()
  115. {
  116. return $this->_resultInfo;
  117. }
  118. /**
  119. * Verification required parameters
  120. * @param string $varName verification item
  121. * @return bool
  122. */
  123. public function required($varName)
  124. {
  125. $result = false;
  126. if (is_array($this->_data) && isset($this->_data[$varName])) {
  127. $result = true;
  128. }
  129. return $result;
  130. }
  131. /**
  132. * Check parameter length
  133. *
  134. * @param string $varName Check item
  135. * @param array $lengthData array($minLen, $maxLen)
  136. * @return bool
  137. */
  138. public function length($varName, $lengthData)
  139. {
  140. $result = true;
  141. /* If this item is not set, the default is verification passed*/
  142. if ($this->required($varName )) {
  143. $varLen = mb_strlen($this->_data[$varName]);
  144. $minLen = $lengthData[0];
  145. $maxLen = $lengthData[1];
  146. if ($varLen < $minLen || $varLen > $maxLen) {
  147. $result = true;
  148. }
  149. }
  150. return $result;
  151. }
  152. /**
  153. * Verification email
  154. * @param string $varName verification item
  155. * @return bool
  156. */
  157. public function email($varName)
  158. {
  159. $result = true;
  160. /* If this item is not set, the default is verification passed*/
  161. if ($this- >required($varName)) {
  162. $email = trim($this->_data[$varName]);
  163. if (preg_match('/^[-w]+?@[-w.]+?$ /', $email)) {
  164. $result = false;
  165. }
  166. }
  167. return $result;
  168. }
  169. /**
  170. * Verify mobile phone
  171. * @param string $varName verification item
  172. * @return bool
  173. */
  174. public function mobile($varName)
  175. {
  176. $result = true ;
  177. /* If this item is not set, the default is verification passed*/
  178. if ($this->required($varName)) {
  179. $mobile = trim($this->_data[$varName]) ;
  180. if (!preg_match('/^1[3458]d{10}$/', $mobile)) {
  181. $result = false;
  182. }
  183. }
  184. return $result;
  185. }
  186. /**
  187. * The verification parameter is a number
  188. * @param string $varName verification item
  189. * @return bool
  190. */
  191. public function digit($varName)
  192. {
  193. $result = false;
  194. if ($this->required($varName) && is_numeric($this->_data[$varName])) {
  195. $result = true;
  196. }
  197. return $result;
  198. }
  199. /**
  200. * The verification parameter is the ID card
  201. * @param string $varName verification item
  202. * @return bool
  203. */
  204. public function ID($ID)
  205. {
  206. }
  207. /**
  208. * The verification parameter is the URL
  209. * @param string $varName verification item
  210. * @return bool
  211. */
  212. public function url($url)
  213. {
  214. $result = true;
  215. /* If this item is not set, the default is verification passed*/
  216. if ($this->required($varName)) {
  217. $ url = trim($this->_data[$varName]);
  218. if(!preg_match('/^(http[s]?::)?w+?(.w+?)$/', $url)) {
  219. $result = false;
  220. }
  221. }
  222. return $result;
  223. }
  224. }
  225. ?>
Copy code


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles