栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

最简单的PHP表单验证库?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

最简单的PHP表单验证库?

我编写了自己的简单类,将多年来收集的一些正则表达式与PHP的sanatize和filter函数结合在一起。

<?class FormValidator{    public static $regexes = Array( 'date' => "^[0-9]{4}[-/][0-9]{1,2}[-/][0-9]{1,2}$", 'amount' => "^[-]?[0-9]+$", 'number' => "^[-]?[0-9,]+$", 'alfanum' => "^[0-9a-zA-Z ,.-_\s?!]+$", 'not_empty' => "[a-z0-9A-Z]+", 'words' => "^[A-Za-z]+[A-Za-z \s]*$", 'phone' => "^[0-9]{10,11}$", 'zippre' => "^[1-9][0-9]{3}[a-zA-Z]{2}$", 'plate' => "^([0-9a-zA-Z]{2}[-]){2}[0-9a-zA-Z]{2}$", 'price' => "^[0-9.,]*(([.,][-])|([.,][0-9]{2}))?$", '2digitopt' => "^d+(,d{2})?$", '2digitforce' => "^d+,dd$", 'anything' => "^[dD]{1,}$"    );    private $validations, $sanatations, $mandatories, $errors, $corrects, $fields;    public function __construct($validations=array(), $mandatories = array(), $sanatations = array())    {        $this->validations = $validations;        $this->sanatations = $sanatations;        $this->mandatories = $mandatories;        $this->errors = array();        $this->corrects = array();    }        public function validate($items)    {        $this->fields = $items;        $havefailures = false;        foreach($items as $key=>$val)        { if((strlen($val) == 0 || array_search($key, $this->validations) === false) && array_search($key, $this->mandatories) === false)  {     $this->corrects[] = $key;     continue; } $result = self::validateItem($val, $this->validations[$key]); if($result === false) {     $havefailures = true;     $this->addError($key, $this->validations[$key]); } else {     $this->corrects[] = $key; }        }        return(!$havefailures);    }        public function getscript() {        if(!empty($this->errors))        { $errors = array(); foreach($this->errors as $key=>$val) { $errors[] = "'INPUT[name={$key}]'"; } $output = '$$('.implode(',', $errors).').addClass("unvalidated");';  $output .= "alert('there are errors in the form');"; // or your nice validation here        }        if(!empty($this->corrects))        { $corrects = array(); foreach($this->corrects as $key) { $corrects[] = "'INPUT[name={$key}]'"; } $output .= '$$('.implode(',', $corrects).').removeClass("unvalidated");';}        $output = "<script type='text/javascript'>{$output} </script>";        return($output);    }        public function sanatize($items)    {        foreach($items as $key=>$val)        { if(array_search($key, $this->sanatations) === false && !array_key_exists($key, $this->sanatations)) continue; $items[$key] = self::sanatizeItem($val, $this->validations[$key]);        }        return($items);    }         private function addError($field, $type='string')    {        $this->errors[$field] = $type;    }        public static function sanatizeItem($var, $type)    {        $flags = NULL;        switch($type)        { case 'url':     $filter = FILTER_SANITIZE_URL; break; case 'int':     $filter = FILTER_SANITIZE_NUMBER_INT; break; case 'float':     $filter = FILTER_SANITIZE_NUMBER_FLOAT;     $flags = FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND; break; case 'email':     $var = substr($var, 0, 254);     $filter = FILTER_SANITIZE_EMAIL; break; case 'string': default:     $filter = FILTER_SANITIZE_STRING;     $flags = FILTER_FLAG_NO_ENCODE_QUOTES; break;        }        $output = filter_var($var, $filter, $flags);     return($output);    }        public static function validateItem($var, $type)    {        if(array_key_exists($type, self::$regexes))        { $returnval =  filter_var($var, FILTER_VALIDATE_REGEXP, array("options"=> array("regexp"=>'!'.self::$regexes[$type].'!i'))) !== false; return($returnval);        }        $filter = false;        switch($type)        { case 'email':     $var = substr($var, 0, 254);     $filter = FILTER_VALIDATE_EMAIL;     break; case 'int':     $filter = FILTER_VALIDATE_INT; break; case 'boolean':     $filter = FILTER_VALIDATE_BOOLEAN; break; case 'ip':     $filter = FILTER_VALIDATE_IP; break; case 'url':     $filter = FILTER_VALIDATE_URL; break;        }        return ($filter === false) ? false : filter_var($var, $filter) !== false ? true : false;    }}

现在,这需要在此处看到的某些javascript的mootools,但是您可以轻松地将其更改为您喜欢的javascript框架。它所做的只是查找元素,并向其中添加“未验证的”
CSS类。

使用就像我一直想要的那样简单:

例:

$validations = array(    'name' => 'anything',    'email' => 'email',    'alias' => 'anything',    'pwd'=>'anything',    'gsm' => 'phone',    'birthdate' => 'date');$required = array('name', 'email', 'alias', 'pwd');$sanatize = array('alias');$validator = new FormValidator($validations, $required, $sanatize);if($validator->validate($_POST)){    $_POST = $validator->sanatize($_POST);    // now do your saving, $_POST has been sanatized.    die($validator->getscript()."<script type='text/javascript'>alert('saved changes');</script>");}else{    die($validator->getscript());}

要仅验证一个元素:

$validated = new FormValidator()->validate('blah@bla.', 'email');

要清理一个元素:

$sanatized = new FormValidator()->sanatize('<b>blah</b>', 'string');

关于此类的最酷的事情是,您可以使用ajax或iframe目标发送表单并执行生成的脚本。无需刷新页面或将相同的表单数据重新发送回浏览器:)此外,如果脚本需要更改,则无需进行过度设计的框架分析,只需按需要进行更改即可:)

哦,是的,随时随地使用此功能。没有许可证



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/421616.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号