【发布时间】:2015-07-05 15:25:49
【问题描述】:
我已经使用 PHP 进行了 php 验证和表单设置。因此,如果有人忘记了用户名,验证将添加到错误数组中,并在提交时显示在页面上。现在,我不想为错误显示一些文本(用户名不能为空),我只希望输入框以红色突出显示,我知道它需要 JavaScript。我在正确运行这个 JavaScript 函数时遇到了一些问题。下面是代码。
JavaScript:
<script type="text/javascript">
function myFunction() {
document.getElementById("usernameformitem").className = "formerror";
}
</script>
PHP:
if (isset($_POST['submit'])) {
$required_fields = array("username");
function validate_presences($required_fields) {
global $errors;
foreach($required_fields as $field) {
//the $value is now the un/pw without whitespaces
$value = trim($_POST[$field]);
//if the value does not exist/is blank
if (!has_presence($value)) {
//remember field is really un or pw
$errors[$field] = fieldname_as_text($field) . " can't be blank";
echo "<script>";
echo "myFunction();";
echo "</script>";
}
}
}
validate_presences($required_fields);
HTML:
<form action="new_user4.php" method="post">
<div id="usernameformitem">
<p>Username:
<input type="text" name="username" value="" />
</p>
</div>
<input type="submit" name="submit" value="Create User" />
</form>
提前致谢!
【问题讨论】:
-
也许 HTML5 输入验证是您的一个选项(以避免 JS)?例如:stackoverflow.com/questions/10281962/…
标签: javascript php css