PHP 常用表单验证类
程序员文章站
2024-01-25 10:38:28
...
<?php header('Content-Type: text/html; charset=utf-8'); class ValidatePost{ //验证是否为指定长度的字母/数字组合 function alphabetLeng($num1,$num2,$str) { return (preg_match("/^[a-zA-Z0-9]{".$num1.",".$num2."}$/",$str))?true:false; } //验证是否为指定长度数字 function numLeng($num1,$num2,$str){ return (preg_match("/^[0-9]{".$num1.",".$num2."}$/i",$str))?true:false; } //验证身份证号码 function identityCard($str){ return (preg_match('/(^([\d]{15}|[\d]{18}|[\d]{17}x)$)/',$str))?true:false; } //验证邮件地址 function email($str){ return (preg_match('/^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,4}$/',$str))?true:false; } //验证电话号码 function phoneNumber($str){ return (preg_match("/^((\(\d{3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}$/",$str))?true:false; } //验证url地址 function url($str){ return (preg_match("/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/",$str))?true:false; } } $vp = new ValidatePost(); if($vp ->alphabetLeng(5, 10, 'onestopweb')){ echo 'alphabetLeng 真'.PHP_EOL; }else{ echo 'alphabetLeng 假'.PHP_EOL; } if($vp ->numLeng(5, 10, '3248185961')){ echo 'numLeng 真'.PHP_EOL; }else{ echo 'numLeng 假'.PHP_EOL; } if($vp ->identityCard('440883199010161234')){ echo 'identityCard 真'.PHP_EOL; }else{ echo 'identityCard 假'.PHP_EOL; } if($vp ->email('onestopweb@163.com')){ echo 'email 真'.PHP_EOL; }else{ echo 'email 假'.PHP_EOL; } if($vp ->phoneNumber('135-12345678')){ echo 'phoneNumber 真'.PHP_EOL; }else{ echo 'phoneNumber 假'.PHP_EOL; } if($vp ->url('http://onestopweb.iteye.com/demo.php?id=12345%name=chaoyi')){ echo 'url 真'.PHP_EOL; }else{ echo 'url 假'.PHP_EOL; }
效果图: