我想遍历提交表单中的所有元素,为每个元素分配自己的变量,然后检查它们是否是必需的。如果他们需要,他们将被检查,如果他们是空的。到目前为止,我的形式如下:通过表单元素循环并检查是否需要
<form id="newitem" action="addnew.php" method="POST">
<label for="title">Title: </label>
<input type="text" name="title" id="title" required="required" /><br />
<label for="description">Description: </label>
<textarea name="description" id="website" cols="40" rows="5" ></textarea><br />
<input type="hidden" name="formsubmit" value="true" /><!-- Option to know we've sumbited the form -->
<input type="submit" value="Submit" id="submit" />
</form>
我那么有它验证使用此:
if (isset($_POST['formsubmit'])) {
// form has been submitted
$errors = Array();
foreach($_POST as $key => $value) {
$$key = $value;
if (!$value) {
array_push($errors, 'Please enter a value for ' . $key);
}
}
if (count($errors) == 0) {
echo 'Form validated';
} else {
showErrors($errors);
}
}
如果元素有一个值这个目前检查。但是,我希望使用HTML required="required"
来检查该字段是否必需。
此外,虽然我觉得我明白这是如何工作的,但我不知道我是否确实如此。我认为$$key = $value
基本上意味着创建一个值为$key
的变量并将其值设为$value
。所以,$key
是元素的名称,而$value
是它的值。但是,我真的没有得到foreach($_POST as $key => $value) {
。我知道它会循环所有的$_POST
,但除此之外我不知道。
感谢您的帮助!
PHP不知道'required'属性。它只接收表单输入'name'和相应的'value'。您可以将整个HTML标记保存在一个字符串中,并使用解析库解析出它们以获取这些属性,但这似乎是不必要的复杂。 – 2012-02-08 12:02:51