Home Backend Development PHP Tutorial php可扩展的验证类实例(可对邮件、手机号、URL等验证)_php技巧

php可扩展的验证类实例(可对邮件、手机号、URL等验证)_php技巧

May 16, 2016 pm 08:11 PM
php

本文实例讲述了php可扩展的验证类。分享给大家供大家参考。具体分析如下:

这里介绍一个可扩展的php验证类,
类里面可以的各类验证可自行调整实现,现在为基本实现方式。
需要添加规则的话, 直接定义方法,方法名即为规则名称。具体参考使用方法。

require_once('./Validator.class.php');
$data = array(
  'nickname' => 'heno' ,
  'realname' => 'steven',
  'age' => 25,
  'mobile' => '1521060426');
$validator = new Validator($data);
$validator->setRule('nickname', 'required');
$validator->setRule('realname', array('length' => array(1,6), 'required'));
$validator->setRule('age', array('required', 'digit'));
$validator->setRule('mobile', array('mobile'));
$result = $validator->validate();
var_dump($result);
var_dump($validator->getResultInfo());

Copy after login

Validator.class.php文件如下:

<&#63;php
/**
 * Validator 数据验证类
 * @package library
 * @category library
 * @author Steven
 * @version 1.0
 */
/**
 * Validator 数据验证类
 * @package library
 * @category library
 * @author Steven
 * @version 1.0
 */
class Validator {
 /**
  * 待校验数据
  * @var array
  */
 private $_data;
 /**
  * 校验规则
  * @var array
  */
 private $_ruleList = null;
 /**
  * 校验结果
  * @var bool
  */
 private $_result = null;
 /**
  * 校验数据信息
  * @var array
  */
 private $_resultInfo = array();
 /**
  * 构造函数
  * @param array $data 待校验数据
  */
 public function __construct($data = null)
 {
  if ($data) {
   $this->_data = $data;
  }
 }
 /**
  * 设置校验规则
  * @param string $var 带校验项key
  * @param mixed $rule 校验规则
  * @return void
  */
 public function setRule($var, $rule)
 {
  $this->_ruleList[$var] = $rule;
 }
 /**
  * 检验数据
  * @param array $data 
  * <code>
  * $data = array('nickname' => 'heno' , 'realname' => 'steven', 'age' => 25);
  * $validator = new Validator($data);
  * $validator->setRule('nickname', 'required');
  * $validator->setRule('realname', array('lenght' => array(1,4), 'required'));
  * $validator->setRule('age', array('required', 'digit'));
  * $result = $validator->validate();
  * var_dump($validator->getResultInfo());
  * </code>
  * @return bool
  */
 public function validate($data = null)
 {
  $result = true;
  /* 如果没有设置校验规则直接返回 true */
  if ($this->_ruleList === null || !count($this->_ruleList)) {
   return $result;
  }
  /* 已经设置规则,则对规则逐条进行校验 */
  foreach ($this->_ruleList as $ruleKey => $ruleItem) {
   /* 如果检验规则为单条规则 */
   if (!is_array($ruleItem)) {
    $ruleItem = trim($ruleItem);
    if (method_exists($this, $ruleItem)) {
     /* 校验数据,保存校验结果 */
     $tmpResult = $this->$ruleItem($ruleKey);
     if (!$tmpResult) {
      $this->_resultInfo[$ruleKey][$ruleItem] = $tmpResult;
      $result = false;
     }
    }
    continue;
   }
   /* 校验规则为多条 */
   foreach ($ruleItem as $ruleItemKey => $rule) {
    if (!is_array($rule)) {
     $rule = trim($rule);
     if (method_exists($this, $rule)) {
      /* 校验数据,设置结果集 */
      $tmpResult = $this->$rule($ruleKey);
      if (!$tmpResult) {
       $this->_resultInfo[$ruleKey][$rule] = $tmpResult;
       $result = false;
      }
     }
    } else {
     if (method_exists($this, $ruleItemKey)) {
      /* 校验数据,设置结果集 */
      $tmpResult = $this->$ruleItemKey($ruleKey, $rule);
      if (!$tmpResult) {
       $this->_resultInfo[$ruleKey][$ruleItemKey] = $tmpResult;
       $result = false;
      }
     }
    }
   }
  }
  return $result;
 }
 /**
  * 获取校验结果数据
  * @return [type] [description]
  */
 public function getResultInfo()
 {
  return $this->_resultInfo;
 }
 /**
  * 校验必填参数
  * @param string $varName 校验项
  * @return bool
  */
 public function required($varName) 
 {
  $result = false;
  if (is_array($this->_data) && isset($this->_data[$varName])) {
   $result = true;
  }
  return $result;
 }
 /**
  * 校验参数长度
  * 
  * @param string $varName 校验项
  * @param array $lengthData array($minLen, $maxLen)
  * @return bool
  */
 public function length($varName, $lengthData)
 {
  $result = true;
  /* 如果该项没有设置,默认为校验通过 */
  if ($this->required($varName)) {
   $varLen = mb_strlen($this->_data[$varName]);
   $minLen = $lengthData[0];
   $maxLen = $lengthData[1];
   if ($varLen < $minLen || $varLen > $maxLen) {
    $result = true;
   }
  }
  return $result;
 }
 /**
  * 校验邮件
  * @param string $varName 校验项
  * @return bool
  */
 public function email($varName)
 {
  $result = true;
  /* 如果该项没有设置,默认为校验通过 */
  if ($this->required($varName)) {
   $email = trim($this->_data[$varName]);
   if (preg_match('/^[-\w]+&#63;@[-\w.]+&#63;$/', $email)) {
    $result = false;
   }
  }
  return $result;
 }
 /**
  * 校验手机
  * @param string $varName 校验项
  * @return bool
  */
 public function mobile($varName)
 {
  $result = true;
  /* 如果该项没有设置,默认为校验通过 */
  if ($this->required($varName)) {
   $mobile = trim($this->_data[$varName]);
   if (!preg_match('/^1[3458]\d{10}$/', $mobile)) {
    $result = false;
   }
  }
  return $result;
 }
 /**
  * 校验参数为数字
  * @param string $varName 校验项
  * @return bool
  */
 public function digit($varName)
 {
  $result = false;
  if ($this->required($varName) && is_numeric($this->_data[$varName])) {
   $result = true;
  }
  return $result;
 }
 /**
  * 校验参数为身份证
  * @param string $varName 校验项
  * @return bool
  */
 public function ID($ID)
 {
 }
 /**
  * 校验参数为URL
  * @param string $varName 校验项
  * @return bool
  */
 public function url($url)
 {
  $result = true;
  /* 如果该项没有设置,默认为校验通过 */
  if ($this->required($varName)) {
   $url = trim($this->_data[$varName]);
   if(!preg_match('/^(http[s]&#63;::)&#63;\w+&#63;(\.\w+&#63;)$/', $url)) {
    $result = false;
   }
  }
  return $result;
 }
}
&#63;>

Copy after login

希望本文所述对大家的php程序设计有所帮助。

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 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.

The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 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.

What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

Using Laravel: Streamlining Web Development with PHP Using Laravel: Streamlining Web Development with PHP Apr 19, 2025 am 12:18 AM

Laravel optimizes the web development process including: 1. Use the routing system to manage the URL structure; 2. Use the Blade template engine to simplify view development; 3. Handle time-consuming tasks through queues; 4. Use EloquentORM to simplify database operations; 5. Follow best practices to improve code quality and maintainability.

PHP and IIS: Making Them Work Together PHP and IIS: Making Them Work Together Apr 21, 2025 am 12:06 AM

Configuring and running PHP on IIS requires the following steps: 1) Download and install PHP, 2) Configuring IIS and adding FastCGI module, 3) Create and set up an application pool, 4) Create a website and bind to an application pool. Through these steps, you can easily deploy PHP applications on your Windows server and improve application stability and efficiency by configuring scaling and optimizing performance.

See all articles