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:
<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;">Create new accountRequest new password</p>
</form>
PHP code for validation:
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 add an html element near the element say
<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
<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; 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.
You can use javascript or jquery for this.
I will illustrate with javascript for your easy understanding.
On your form, change the first line to
<form method="post" action="login.php" onsubmit="return check_error();">
and add a javascript section
<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.
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 also use HTML 5 new feature of reququired attribute on input tags. 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. 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. And its design can be maintained by CSS with new css selectors too. 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>
Related
let me explain this better, i would like to know how it's possible to create a js code that checks if an html input is correct and in case it is it redirects you to another page, here is what i tried based on what i managed to find out.
html part:
<form name="access" onsubmit="return validate()">
<input
type="text"
id="inputbox"
value="Password"
pattern="idkwhatishoouldwriteinhere"
/>
<input type="submit" value="Submit" />
</form>
js part:
function validate() {
if (document.access.Password.value != "idkwhatishoouldwriteinhere") {
alert("Wrong password");
document.access.Password.focus();
return false;
} else {
window.open("index.html");
}
}
in case you are wondering why i put the "answer" in the patter is because this is supposed to be a little easter egg and i feel like looking directly at the js is meaningless becuase it contains the link you should be redirected to.
enter code here
You need to give your input the name Password, otherwise document.access.Password is undefined.
function validate() {
if (document.access.Password.value != "idkwhatishoouldwriteinhere") {
alert("Wrong password");
document.access.Password.focus();
return false;
} else {
window.open("index.html")
}
}
<form name="access" onsubmit="return validate()">
<input type="text" id="inputbox" value="Password" name="Password" />
<input type="submit" value="Submit" />
</form>
<!-- password is "idkwhatishoouldwriteinhere" -->
You want this.
You had some issues with the id of the field and name etc
I also changed your inline code to eventListener which is the recommended method
Password is fred
window.addEventListener("load", function() {
document.getElementById("access").addEventListener("submit", function(e) {
const inputbox = document.getElementById("inputbox");
if (inputbox.value != "fred") {
alert("Wrong password");
inputbox.focus();
e.preventDefault(); // cancel submit
} else location.replace("index.html")
});
})
<form id="access">
<input type="password" id="inputbox" value="" placeholder="Password" />
<input type="submit" value="Submit" />
</form>
If you want to keep your code close to what you already have, I would adjust it like this. I would suggest storing your class names and ids as variables and then accessing them from the variable. Also there is no need to return false in your if. There are other good solutions on here but this one will keep your code pretty close. This will also ensure that you don't end up with a null value when accessing the value in your password field.
const passwordField = document.getElementById('inputbox');
function validate() {
if(passwordField.value != "idkwhatishoouldwriteinhere") {
alert( "Wrong password" );
passwordField.focus() ;
}
else {
window.open("index.html")
}
}
<form name="access" onsubmit="validate()" href="javascript:void(0)">
<input type="text" id="inputbox" value="Password" />
<input type="submit" value="Submit" />
</form>
I have a script that I have been using for a few years and it works on everything I use it on. It seems to be broken all of a sudden on a new script I am using it on.
I need for it to check that First Name was filled out and that the email address entered is a Gmail email address only.
I am hoping that someone can look at the code and let me know if I am missing something, or show me a better way to do this.
Here is my code:
<form name="myForm" method="post" action="putform3.php" onsubmit="return validateForm()">
<div class='card-img-top' style="position: relative; width: 300px; padding: 5px; background-color: #989eae;"><center>
<b>Fill Out The Form Below</b><br />
<input class='card-img-top' name="fname" type="text" value="" style="width:280px; margin-bottom:5px; color:#000000;" placeholder="First Name" required /><br />
<input class='card-img-top' name="email" type="text" value="" style="width:280px; margin-bottom:5px; color:#000000;" placeholder="Gmail Email" required /><br />
<input type="hidden" name="affiliate" value="$affiliate" />
<input type="hidden" name="myip" value="$ip" />
<input type="hidden" name="lp" value="$lp" />
<input class="formbutton" type="submit" name="submit" value="$buttontext"><br />
<span style="font-size: 10px;">We keep your information private!</span>
</center></div>
</from>
<script type="text/javascript">
function validateForm()
{
var e=document.forms["myForm"]["email"].value;
var f=document.forms["myForm"]["fname"].value;
var atpos=e.indexOf("#");
var dotpos=e.lastIndexOf(".");
var gmail = e.split("#");
var rgmail = gmail[1];
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=e.length)
{
alert("Not a valid e-mail address");
return false;
}
if (rgmail == "yahoo.com" || rgmail == "hotmail.com" || rgmail == "msn.com" || rgmail == "aol.com" || rgmail == "yandex.com")
{
alert("Must Be A Good gmail.com Email Address");
return false;
}
if (f==null || f=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
The javascript is totally being ignored. It's not that it's not working but it's never being used. I am totally lost here as it works on all my other scripts. I even put an alert('worked'); in the script to be sure it was being used and it's not showing the alert.
As per the website link provided:
There were multiple js issues on website which causes js validation function to run properly are:
use https: instead of http for jquery file include url
inside script.js file window.getComputedStyle is undefined
remove additional lname value line inside validation function as
there is no such input in the form
Here is the code, I can't figure out why enter/return isn't working! Is it because it's inline?
HTML
<div class="wrap"><form name="login" style="margin: 0px">
<label for="fname">CLICK TO ENTER PASSWORD</label>
<input TYPE="text" NAME="pass" size="17" onKeyDown="e.keyCode == 13;" id="fname" class="cool"><br><input type="button" value="LOGIN" class="asbestos-flat-button" onClick="TheLogin(this.form)">
</form>
</div>
JS
<script language="JavaScript" type="text/javascript">
<!--- PASSWORD PROTECTION SCRIPT
function TheLogin() {
var password = 'password';
if (this.document.login.pass.value == password) {
top.location.href="home.html";
}
else {
location.href="index.html";
}
}
// End hiding --->
</script>
I'm learning JS so any help would be so awesome!
UPDATE
Thanks for your help. Still not working when integrated. The page doesn't load the home.html when I hit enter/return. Instead I get no refresh, and the address bar has the url http://example.com/?pass=password.
If I click the button it does load the home.html!
thanks!
Here I wrote a JSFiddle with the working example.
In the HTML code:
Remove onKeyDown="e.keyCode == 13;" from the <input> text element.
Remove onClick="TheLogin(this.form)" from the <input> button element.
Change the type of input button from 'button' to 'submit'. In this way, when you press "enter" in the input text form the form is submitted.
Intercept the "submit" event in the form, adding onSubmit="theLogin(this.form)" on <form> element.
Note: I have renamed the function name from "TheLogin" to "theLogin" because in JavaScript the functions begins with lowercase letters if they are not constructors.
The HTML code:
<div class="wrap">
<form name="login" style="margin: 0px" onSubmit="theLogin(this.form)">
<label for="fname">CLICK TO ENTER PASSWORD</label>
<INPUT TYPE="text" NAME="pass" size="17" id="fname" class="cool">
<br>
<input type="submit" value="LOGIN" class="asbestos-flat-button">
</form>
</div>
And the JavaScript code:
theLogin = function() {
var password = 'password';
if (this.document.login.pass.value === password) {
top.location.href = "home.html";
} else {
location.href = "index.html";
}
}
You have missed the <input type="submit">, without it you can't use the Enter key to submit the form.
Alright, so I don't know if this is possible, or if there is an easier way to do what I'm trying to accomplish.
Basically I am using a Javascript form to enter in a username and password with a login button. If the username and password are entered correctly and you hit the login button, I would like the page to hide the "login form", and run another form. or if there is a way to disable the "patient info form" until the "login form" has been entered correctly.
I am completely lost on how to do this. Any help would be appreciated!
This is what I have so far.
<form name="recLogin">
<table>
<th>Receptionist Login</th>
<tr><td>Username:
<input type="text"
name="txtUsername"
id="username"
placeholder="Username"
value="mayo" required ></td>
<td>Password:
<input type="password"
name="txtPassword"
id="password"
placeholder="Password"
value="Please99!" required ></td>
<td><input type="button"
onClick="validateLogin();"
value="Login"></td></tr>
</table>
</form>
<form name="patientInfo">
<table>
<th>Patient Information</th>
<tr><td>First Name:
<input type="text"
name="txtFName"
id="firstName"
placeholder="First Name";
value=""></td></tr>
<tr><td>Last Name:
<input type="text"
name="txtLName"
id="lastName"
placeholder="Last Name"
value=""></td></tr>
</table>
Javascript Code
function validateLogin()
{
var notValid = true;
var username = document.forms["recLogin"]["txtUsername"].value;
var password = document.forms["recLogin"]["txtPassword"].value;
username = username.toLowerCase();
if(username == "mayo" && password == "Please99!")
{
/*****COMPLETELY STUCK******/
alert("Entered Correctly");
notValid = false;
}
else
{
alert("I'm sorry but the username and password you entered are incorrect, please try again.");
}
}//End of validateLogin()
Just as barmar mentioned,
Apply table ids like
<table id='receiptionist_table' style='display:block'>
<th>Receptionist Login</th>
the block means this table will be shown when you first come on the page.
and
<table id='Patient_table' style='display:none'>
<th>Patient Information</th>
we are using display none so that this form is hidden, you will now change styles inside your script as soon as login is successful which is:
if(username == "mayo" && password == "Please99!")
{
document.getElementById('receiptionist_table').style.display='none';
document.getElementById('Patient_table').style.display='block';
alert("Entered Correctly");
notValid = false;
}
In the script you need to just play with styles. That's it!
I hope this fixes your issue.
I have a php contact form with some js script. In that form when the submit button (input) is clicked (if all the inputs are filled correctly) a "success" message will appear under the form, but it can't be seen because the page is redirecting to the contact.php file. I want the form to work without redirecting, so just to appear that success message under the form and to CLEAR all the inputs after submit (if all the inputs was filled correctly). I would really appreciate any help! Thanks in advance.
I can't put php in jsfiddle, but I think it is not needed for what I want.
Here is the rest of the code.
http://jsfiddle.net/5nLab5kh/
HTML:
<form role="form" id="form-contact" method="post" action="php/contact.php">
<div class="form-group">
<label for="ContactName">Your Name (required)</label>
<input type="text" class="form-control required" name="ContactName" id="ContactName" value=""/>
</div>
<div class="form-group">
<label for="ContactEmail">Email Address (required)</label>
<input type="email" class="form-control required" name="ContactEmail" id="ContactEmail" value="" />
</div>
<div class="form-group">
<label class="ContactMsg">Your Message</label>
<textarea class="form-control" rows="3" name="ContactMsg" title=""></textarea>
</div>
<input type="submit" class="btn btn-primary" value="Submit" name="submit" id="ContactMessage"/>
</form>
<p id="cf-notification"></p>
JS:
$('#form-contact').submit(function(){
/* Get Values */
contact_name = $('#ContactName').val();
contact_email = $('#ContactEmail').val();
contact_message = $('#ContactMsg').val();
/* Validate Fields */
if( contact_name == '' ){
$('#cf-notification').hide().html('<span class="alert"><i class="fa fa-exclamation-triangle"></i>Please fill your contact name!</span>').fadeIn("slow");
return false;
}else if( contact_email == '' ){
$('#cf-notification').hide().html('<span class="alert"><i class="fa fa-exclamation-triangle"></i>Please fill your email address!</span>').fadeIn("slow");
return false;
}else if( contact_message == '' ){
$('#cf-notification').hide().html('<span class="alert"><i class="fa fa-exclamation-triangle"></i>Please fill your message!</span>').fadeIn("slow");
return false;
}else{$('#cf-notification').hide().html('<span class="success"><i class="fa fa-envelope"></i>' + 'Thank you for contacting us! We will answer as soon as we can.' + '</span>').fadeIn("slow");
return true;
}
});
It was solved. For who is interested in "else" you have to replace "return true" with this:
$("#form-contact")[0].reset();
$.post($(this).attr('action'), $(this).serialize(), function(response){
},'json');
return false;
The first line is just clearing the inputs, the rest is solving the redirect problem :). So works perfectly and no redirect.