我在上一篇文章中讲到使用javascript做集成表单验证的方法,对于客户端验证已经足够,但好的表单验证应同时在客户端和服务器端进行——这正是写本文的目的。
如果采用一般的验证方法应该怎样写呢?
if ($_POST['some'] 不满足 condition) {
die("wrong");
}
类似于javascript的集成验证方法,在PHP中也可利用数组和eval语句实现表单验证(服务器端)框架。一般步骤:
1、将用户提交的数据从$_GET或$_POST数组收集到自定义数组(可选),
2、填充验证数组(包括变量名、条件及提示等),
3、添加固定的验证代码。
下面我来举例说明,假设你要从网页中收集用户姓名及年龄,并且在服务器端实现数据验证,那么你可能需要form.html和act.php。form.html中包含表单:
act.php中将实现表单的验证:
$userinfo = array(); // 步骤1
$userinfo['name'] = isset($_POST['uname']) ? $_POST['uname'] : '';
$userinfo['age'] = isset($_POST['uage']) ? (int)$_POST['uage'] : 0;
$error_message = ""; // 错误信息
// 步骤2
$elems = array(
array("\$userinfo['name']", 'strlen(#)
// 若省略步骤1则按如下方式改写:
// array("\$_POST['uname']", 'strlen(#)
array("\$userinfo['age']", '#
);
// 步骤3
for($i = 0; $i if(eval("if(".preg_replace("/[#]/", $elems[$i][0], $elems[$i][1]).") return false;") === false) {
$error_message .= $elems[$i][2];
}
}
这样,我们每次只须填充验证数组$elems就可完成表单验证。
希望对你们有用,我也很想知道你们是怎么做的。
这样,我们每次只须填充验证数组$elems就可完成表单验证。
希望对你们有用,我也很想知道你们是怎么做的。
这样,我们每次只须填充验证数组$elems就可完成表单验证。
希望对你们有用,我也很想知道你们是怎么做的。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

WebStorm Mac version
Useful JavaScript development tools
