简体   繁体   English

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

[英]How to add Text box validation in webpage?

Hi I have two text boxes. 嗨,我有两个文本框。 One is for username and other one is for password. 一种用于用户名,另一种用于密码。 Currently I have code for displaying a error message saying "Invalid credentials" if any of the fields are left blank. 当前,我有代码用于显示错误消息,如果其中任何字段为空,则显示“无效的凭据”。 This takes me to the new page displays the error message and takes me back to the home page where I can enter my username and password again. 这将我带到新页面,显示错误消息,并带我回到主页,可以再次输入用户名和密码。

I want the validation part to be done near the text box itself. 我希望验证部分在文本框本身附近完成。 For example if Username textbox is left blank and submit button is clicked, it should display a message like Please enter the username near the textbox itself. 例如,如果“用户名”文本框留为空白并且单击了“提交”按钮,它将显示一条消息,如“请在文本框本身附近输入用户名”。

HTML code: 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 code for validation: 用于验证的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>'; 

} 

You can use javascript or jquery for this. 您可以为此使用javascript或jquery。 I will illustrate with javascript for your easy understanding. 为了方便您理解,我将使用javascript进行说明。

On your form, change the first line to 在表单上,​​将第一行更改为

<form method="post" action="login.php" onsubmit="return check_error();">

and add a javascript section 并添加一个javascript部分

<script>
function check_error(){
   if(document.getElementById('username_id').value == ""){
      alert("Enter The Username");
      return false;
   }
}
</script>

You will need to add the "ID" for each textbox you would like to be verified. 您需要为要验证的每个文本框添加“ ID”。

Try this--- 尝试这个 - -

<script language="javascript">
function check_error(){
    if(document.getElementById('username').value == ""){
        alert('Please Enter Username');
        return false;
    }
}
</script>
<form method="post" onSubmit="check_error();">
<input type="text" name="username" id="username" />
<input type="submit" value="Submit" />
</form>

It is a very simple demonstration. 这是一个非常简单的演示。 but you can certainly build on it. 但您当然可以在此基础上建立。

You can add an html element near the element 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>

Then 然后

using jQuery 使用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>

the return false; return false; to stop the submitting. 停止提交。

For checking if the username is empty just do this: 要检查用户名是否为空,只需执行以下操作:

if($_POST['username']=''){
   echo 'Please enter the username';
}

If you want this near your textbox, just put it in place where the text will be showing as close to the textbox, so at the beginning of submitting the button. 如果您想在文本框附近放置它,只需将其放置在文本将显示在文本框附近的位置,因此在开始提交按钮时就可以使用。 If you want that when this error is showing he shouldn't actually login. 如果您希望在显示此错误时显示该信息,那么他实际上不应登录。 You could use a boolean like so: 您可以像这样使用布尔值:

$check=true;
if ($_POST['submit']) { 
   if($_POST['username']=''){
   echo 'Please enter the username';
   $check=false;
   }
   if($check){
   //everything you want to do if it's succesfull
   }
}

This will make sure when the $check=false it wont go to the next page but stay on the current page, displaying the error message. 这样可以确保当$check=false它不会转到下一页,而是停留在当前页面上,并显示错误消息。

You can also use HTML 5 new feature of reququired attribute on input tags. 您还可以在输入标签上使用HTML 5 必需属性的新功能。 LIKE an example of : 例如:

<input type='text' name='txt_username' required='true' />
<input type='password' name='txt_password' required='true'/>

To use that above feature, you should need to declare 要使用上述功能,您需要声明 before elements. 在元素之前。

You can also set custom error meesage using "oninvalid" event and setCustomValidity("") function. 您还可以使用“ oninvalid”事件和setCustomValidity(“”)函数来设置自定义错误消息。 A example : 一个例子:

<input type='text' name='txt_photo_title' value='' required='true' placeholder="photo name" oninvalid="setCustomValidity('Please Enter Photo Name !');" />

And some sample login form is shown as below. 并且一些示例登录表单如下所示。 Due to HTML 5 new features, sdata don't reach to sever actually, it excutes in user's browser and so after click submit button, it show error msg instantly. 由于HTML 5的新功能,sdata实际上并没有被切断,它在用户的浏览器中执行,因此在单击Submit按钮后,它立即显示错误msg。 And its design can be maintained by CSS with new css selectors too. 并且CSS的设计也可以通过新的CSS选择器来维护。 Thanks and try it as below sample. 谢谢,请尝试以下示例。

<!DOCTYPE HTMl>
<html>
<head>
    <title> Test Form</title>
</head>
<body>
    <h1> Test Validation Form</h1>
    <hr>

    <form name='frm_test' method='post' action='login.php' > 
        <label> Username :</label>
        <input type='text' name='txt_username' required='true' oninvalid="setCustomValidity('Please enter username !');"/>
        <br/>
        <label> Password :</label>
        <input type='password' name='' required='true' oninvalid="setCustomValidity('Please Enter passwords !');"/>

        <input type='submit' name='btn_submit' value='Login'>
    </form>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM