gpt4 book ai didi

javascript - 如何在网页中添加文本框验证?

转载 作者:行者123 更新时间:2023-11-28 20:10:55 25 4
gpt4 key购买 nike

嗨,我有两个文本框。一张用于用户名,另一张用于密码。目前,如果任何字段留空,我有用于显示错误消息“无效凭据”的代码。这会将我带到显示错误消息的新页面,并将我带回到主页,我可以在其中再次输入我的用户名和密码。

我希望验证部分在文本框本身附近完成。例如,如果“用户名”文本框留空并单击“提交”按钮,则应显示一条消息,例如“请在文本框本身附近输入用户名”。

HTML 代码:

<form method="post" action="login.php">
<p class="user_text">USER LOGIN</p>
<p class="user_name_text">username<span style="color:#f60219;"> *</span></p>
<p style="padding:8px 0 0 5px;">

<input type="text" name="username" minlength="2" maxlength="20" class="contact_filed" value="enter your name" onfocus="javascript:clearField(this,'enter your name')" onblur="javacript:fillField(this,'enter your name')" /></label>
</p>
<p class="user_name_text1">password<span style="color:#f60219;"> *</span></p>
<p style="padding:8px 0 0 5px;">
<input type="password" name="password" maxlength="20" class="contact_filed" value="password" onfocus="javascript:clearField(this,'password')" onblur="javacript:fillField(this,'password')" />
</p>
<p style="padding:16px 0 0 16px;"><input name="submit" type="submit" value="Submit" class="log" /></p>
<p style="padding:12px 0 0 16px;"><a href="#" class="read_more1">Create new account</a><a href="#" class="read_more1">Request new password</a></p>
</form>

用于验证的 PHP 代码:

if ($_POST['submit']) { 
include('connect.php');
$u = mysql_real_escape_string($_POST['username']);
$p = md5($_POST['password']);
$q = mysql_query("SELECT id FROM $login_db_table WHERE username='$u' AND password='$p' LIMIT 1");

if (mysql_fetch_array($q, MYSQL_ASSOC)) {
if ($_POST['remember']) {
setcookie('username', $_POST['username'], time() + 5000000);
setcookie('password', md5($_POST['password']), time() + 5000000);
} else {
setcookie('username', $_POST['username']);
setcookie('password', md5($_POST['password']));
}


if($u != "" && $p !=""){
echo '<p>Login successful.</p>';
header("Location: main.php");
}

}

else
echo "Login failed. Please enter valid credentials.";
echo "<script>setTimeout(\"location.href = 'http://localhost/CashTree/reg/Home/index.html';\",1500);</script>";
//echo '<p>Login failed. Please enter your correct credentials</p>';

}

最佳答案

您可以在元素 say 附近添加一个 html 元素

    <p style="padding:8px 0 0 5px;">

<input id="uname" type="text" name="username" minlength="2" maxlength="20" class="contact_filed" value="enter your name" onfocus="javascript:clearField(this,'enter your name')" onblur="javacript:fillField(this,'enter your name')" />
<div id="user_name_invalid"></div>
</p>

然后

使用 jQuery

<script type='text-javascript'>
$("#form").submit(function(e){
var uname = $("#username").val();
if(uname == ""){
$("#user_name_invalid").html("Username is invalid");
return false;
}
}
</script>

return false; 停止提交。

关于javascript - 如何在网页中添加文本框验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19923959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com