search

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> * $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> * </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 $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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools