在PHP中快速验证表单字段

时间:2011-07-17 22:11:03

标签: php forms validation

当我在form标记下有字段时,我使用isset()函数,如下所示:

if(isset($_POST) and isset($_POST['title']) and $_POST['date'])
{
   //something;
}

当我验证更多字段时,它会变大。我正在寻找任何简单的方法来验证它们是否都在服务器端用PHP填充。

可能导航所有字段并检查它们是否按要求填充。

5 个答案:

答案 0 :(得分:4)

<?php

$fields = array('field1', 'field2', 'field3', ...etc...); //  Array of fields

$valid = true;  //Assume all fields are correct and set this to false if not

foreach($fields as $field) {
    if(!array_key_exits($field, $_POST)) { 
        $valid = false; // At least one key isn't set
        break;
    }
}

if($valid) {
    // All fields are good
} else {
    //Your user failed...
}

答案 1 :(得分:4)

// required fields
$fields = array('title', 'date', 'email');

// optionally ignore blank posted values
$_POST = array_filter(array_map('trim', $_POST), 'strlen');

if (count(array_intersect_key($_POST, array_flip($fields))) == count($fields))
{
    // all the required fields were posted
}

else
{
    // ...not
}

答案 2 :(得分:1)

$_POST是一个数组,因此您可以使用foreach获取其元素,然后测试每个元素是否为空或否,如果存在,则会收集错误,并在最后发送一条错误消息。< / p>

答案 3 :(得分:0)

我在PHP手册的评论部分找到了它...

将数组作为键的小函数:

<?php
//note the s in the function name (keys)
function array_keys_exists($array,$keys) {
    foreach($keys as $k) {
        if(!isset($array[$k])) {
        return false;
        }
    }
    return true;
}
?>
//useful to validate a form for example
<form>
    <input type="text" name="field1" /><br />
    <input type="text" name="field2" /><br />
    <input type="text" name="field3" /><br />
    <input type="text" name="field4" /><br />
    <input type="text" name="field5" /><br />
</form>
<?php
if(!array_keys_exists($_POST,
array("field1","field2","field3","field4","field5")
)) {
    //some fields are missing, dont do anything (maybe hacking)
} else {
    //code ...
}
?>

答案 4 :(得分:0)

更可重用的解决方案是编写一个小函数来验证密钥列表是否存在,例如

function array_keys_exist($keys, $search) {
    // If we were passed a single key, use existing function
    if (!is_array($keys)) {
        return array_key_exists($keys, $search);
    }
    // If there are no keys in $search that are not in $keys
    // We have all the keys
    return 0 == count(array_diff($keys, array_keys($search)));
}

然后可以用于所有形式:

$requiredFields = array('title', 'date', 'details');
if (array_keys_exist($requiredFields, $_POST)) {
    // Do your thing
}

坦率地说,我不确定为什么这不是一个内置函数