Trying to validate a form but I am facing constant problems. Here is the code
HTML:
<form id="regForm" class="form-group" method="POST" action="signup.php">
<div class="col-md-12">
<h2>Job Pocket</h2>
</div>
<div class="col-md-12">
<input placeholder="email" class="form-control"type="text" name="email" id="email">
</div>
<div class="col-md-12">
<input placeholder="password" class="form-control" type="password" name="password" id="password">
</div>
<div class="col-md-12">
<input placeholder="confirm password" class="form-control" type="password" name="confirmpass" id="confirmpass">
</div>
<div class="container">
<div class="row">
<div class="col-md-6">
<input placeholder="first name" class="form-control" type="text" name="first_name" id="first_name">
</div>
<div class="col-md-6">
<input placeholder="last name" class="form-control" type="text" name="last_name" id="last_name">
</div>
</div>
</div>
<div class="col-md-12">
<input type="submit" onclick="return validation()"class="btn btn-primary"name="submitsignup" id="submitsignup" value="submit">
</div>
<hr>
</form>
</div>
</div>
</div>
</div>
</div>
</main>
<p id="mg"></p>
</div>
JavaScript:
<script type="text/javascript">
function validation(){
if(document.getElementById("email").value=="" || document.getElementById("password").value=="" || document.getElementById("last_name").value=="" || document.getElementById("first_name").value==""){
document.getElementById("mg").innerHTML="Fill all fields";
return false;
}
var emails = document.getElementById("email").value;
else if(emails.indexOf('#') <= 0){
document.getElementById('mg').innerHTML =" ** # Invalid Position";
return false;
}
else if((emails.charAt(emails.length-4)!='.') && (emails.charAt(emails.length-3)!='.')){
document.getElementById('mg').innerHTML =" ** . Invalid Position";
return false;
}
else {
document.getElementById("regForm").submit();
}
}
</script>
The form keeps submitting itself. It works for the first if statement but after that it ignores the two else if and submits itself.
Even if I comment out this statement, it still submits to signup.php
document.getElementById("regForm").submit();
At the moment I have no idea why it is submitting so I am adding the php code aswell.
if(isset($_POST['submitsignup'])){
$date = array();
if($_POST['email']=='' || $_POST['password']=='' || $_POST['first_name']=='' || $_POST['last_name']==''){
$template->error="Please fill all fields";
}}
I added this bit of code in the signup.php file for an extra check but I have seen that it strightup submits to signup.php.
EDIT: Updated answer to updated question
Your problem might be related to the fact that you have this line of code:
var emails = document.getElementById("email").value;
before the elseif, which might break the if elseif flow.
Try using this code instead:
function validation(){
var emails = document.getElementById("email").value;
if(emails=="" || document.getElementById("password").value=="" || document.getElementById("last_name").value=="" || document.getElementById("first_name").value==""){
document.getElementById("mg").innerHTML="Fill all fields";
return false;
}
else if(emails.indexOf('#') <= 0){
document.getElementById('mg').innerHTML =" ** # Invalid Position";
return false;
}
else if((emails.charAt(emails.length-4)!='.') && (emails.charAt(emails.length-3)!='.')){
document.getElementById('mg').innerHTML =" ** . Invalid Position";
return false;
}
else {
document.getElementById("regForm").submit();
}
}
Try with:
<input type="button"
instead:
type="submit"
Edit: otherwise your .submit() function is useless.
-2 ? Tell me why using .submit() if the form as already submit type ?
Related
I am trying to make a functional login and registration pages (I know that in real life I need to store the login info in a database but for now I would like to see my pages "working"). I created two pages with forms one for registration and one for login. I also have two JS files one for locally storing input values (registerDetails.js) and one for retrieving those values during login (login.js).
Storing the information is not a problem, however, when I try to log in with the information I have just inputted and know it's correct it still throws an "Error" at me to say that password and username don't match even though I know they do match.
SOLUTION IN THE COMMENTS - MIX UP OF VARIABLES
I even tried to error handle if there is a problem with browser compatibility, still to no avail.
This is HTML for register.html:
<form class="form-horizontal">
<fieldset>
<div id="legend">
<legend>
Register or <a class="login-link" href="login.html">Login</a>
</legend>
<p>All fileds marked with * are required.</p>
</div>
<hr />
<div class="control-group">
<!-- Username -->
<label class="control-label" for="username"><span class="asterisk">*</span> Username</label>
<div class="controls">
<input type="text" id="username" name="username" placeholder="Any letters or numbers without spaces"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- E-mail -->
<label class="control-label" for="email"><span class="asterisk">*</span> E-mail</label>
<div class="controls">
<input type="text" id="email" name="email" placeholder="Enter your email here" class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="password"><span class="asterisk">*</span> Password</label>
<div class="controls">
<input type="password" id="password" name="password" placeholder="Password of atleast 4 characters"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Password -->
<label class="control-label" for="password_confirm"><span class="asterisk">*</span> Confirm Password</label>
<div class="controls">
<input type="password" id="password_confirm" name="password_confirm" placeholder="Please confirm password"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button type="submit" id="register" class="btn btn-success" onClick="store()">
Register
</button>
</div>
</div>
</fieldset>
</form>
Here is my HTML for login.html:
<form class="form-horizontal">
<fieldset>
<div id="legend">
<legend>
Login or <a class="login-link" href="register.html">Register</a>
</legend>
</div>
<hr />
<div class="control-group">
<!-- Username or Email-->
<label class="control-label" for="username">Username or Email</label>
<div class="controls">
<input type="text" id="usernameEmail" name="usernameEmail" placeholder="Enter your email or username"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" id="passwordLogin" name="password" placeholder="Enter your password"
class="input-xlarge" />
</div>
<br />
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success" type="submit" onclick="check()">Login</button>
</div>
</div>
</fieldset>
</form>
My registration JS works fine, the browser prompts me to save credentials for later use...
Which is here:
// Getting details from the registration form to later store their values
var userName = document.getElementById('username');
var userEmail = document.getElementById('email');
var password = document.getElementById('password');
var passwordConfirm = document.getElementById('password_confirm');
// Locally storing input value from register-form
function store() {
if (typeof (Storage) !== "undefined") {
localStorage.setItem('name', userName.value);
localStorage.setItem('email', userEmail.value);
localStorage.setItem('password', password.value);
localStorage.setItem('password_confirmation', passwordConfirm.value);
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
My login page, however, throws the ERROR alert, even when I know for sure that the username and password match.
// check if stored data from register-form is equal to entered data in the login-form
function check() {
// stored data from the register-form
var storedName = localStorage.getItem('name');
// var storedEmail = localStorage.getItem('email');
var storedPassword = localStorage.getItem('password');
// entered data from the login-form
var userNameLogin = document.getElementById('usernameEmail');
var userPwLogin = document.getElementById('passwordLogin');
// check if stored data from register-form is equal to data from login form
if (userNameLogin.value == storedName && storedPassword.value == userPwLogin) {
alert('You are loged in.');
} else {
alert('ERROR.');
}
}
I have spent a few hours trying to rewrite the code to maybe see some typos or mistakes but I cannot find where I am going wrong! If anyone could help out as to show the reason why it does not match the username and password would be great.
It should alert me "You are logged in."
Thanks!
You have a typo
if (userNameLogin.value == storedName && storedPassword.value == userPwLogin) {
^^Here
}
Should be this instead
if (userNameLogin.value == storedName && userPwLogin.value == storedPassword ) {
}
By the way, your code will only log in with username (and not email) as it is. Don't forget to compare the email too.
Variables that are meant to store your elements at register page(userName, userEmail, etc.) might be null when store() is called.
I would suggest to get those inside the function:
function store() {
var userName = document.getElementById('username');
var userEmail = document.getElementById('email');
var password = document.getElementById('password');
var passwordConfirm = document.getElementById('password_confirm');
if (typeof (Storage) !== "undefined") {
localStorage.setItem('name', userName.value);
localStorage.setItem('email', userEmail.value);
localStorage.setItem('password', password.value);
localStorage.setItem('password_confirmation', passwordConfirm.value);
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
But the solution lies in this line:
if (userNameLogin.value == storedName && storedPassword.value == userPwLogin)
In your case storedPassword doesn't have "value" and userPwLogin does, since userPwLogin is the element on your form
Your code isn't working right because you've mixed up your local storage variable with your input elements. This line:
if (userNameLogin.value === storedName && storedPassword.value === userPwLogin) {
it should be:
if (userNameLogin.value === storedName && userPwLogin.value === storedPassword) {
Good morning,
I'm working on some simple form validation. Whenever I submit my form, the error message appears, but I can repeatedly spam the button for numerous error messages. Is there a way I can change this to only show the error message once? I've also noticed that even if I populate both fields it will still flash quickly in my console with the error log but not show the error.
Can anyone tell me what I'm doing wrong here?
var uname = document.forms['signIn']['userame'].value;
var pword = document.forms['signIn']['password'].value;
function validateMe (e) {
if (uname.length || pword.length < 1 || '') {
var container = document.getElementById('error-container');
var errorMsg = document.createElement('div');
errorMsg.className = 'error-message';
errorMsg.innerHTML = '<span class="heading-large">Please enter a valid username or password</span>';
container.appendChild(errorMsg);
console.log('An error occured');
return false;
}
}
<form id="signIn" action='#'>
<div class="boxed left-floater">
<h1 class="heading-large margin-top">Sign in</h1>
<div id="error-container"></div>
<div class="form-group">
<label class="form-label-bold" for="username">Username</label>
<input class="form-control log-in-form-control" id="username" name="username" type="text">
</div>
<div class="form-group">
<label class="form-label-bold" for="password">Password</label>
<input class="form-control log-in-form-control" id="password" type="password" name="password">
</div>
<div>
<a class="right-floater forgotten-password" href="forgottenpassword.html">Forgotten Password</a>
<button class="button clear right-floater" type="submit" onclick="validateMe();">Sign In</button>
</div>
</div>
</form>
Fiddle
You must be clearing the contents of your container to avoid duplication of elements. Below are few things to note:
You were trying to get userame instead of username in your fiddle. May be spelling mistake.
Keep input type=submit instead of button
Pass the event to your validateMe function to prevent the default action of post.
Move the variables within the function to get the actual value all the time
function validateMe(e) {
e.preventDefault();
var uname = document.forms['signIn']['username'].value;
var pword = document.forms['signIn']['password'].value;
var container = document.getElementById('error-container');
container.innerHTML = ''; //Clear the contents instead of repeating it
if (uname.length < 1 || pword.length < 1) {
var errorMsg = document.createElement('div');
errorMsg.className = 'error-message';
errorMsg.innerHTML = '<span class="heading-large">Please enter a valid username or password</span>';
container.appendChild(errorMsg);
console.log('An error occured');
return false;
}
}
<form id="signIn" action='#'>
<div class="boxed left-floater">
<h1 class="heading-large margin-top">Sign in</h1>
<div id="error-container"></div>
<div class="form-group">
<label class="form-label-bold" for="username">Username</label>
<input class="form-control log-in-form-control" id="username" name="username" type="text">
</div>
<div class="form-group">
<label class="form-label-bold" for="password">Password</label>
<input class="form-control log-in-form-control" id="password" type="password" name="password">
</div>
<div>
<a class="right-floater forgotten-password" href="forgottenpassword.html">Forgotten Password</a>
<input value="Sign In" class="button clear right-floater" type="submit" onclick="validateMe(event);" />
</div>
</div>
</form>
Updated Fiddle
Edit - if condition was failing and have updated it accordingly
this is full work code
var uname = "";
var pword = "";
function validateMe(e) {
e.preventDefault();
uname = document.forms['signIn']['username'].value;
pword = document.forms['signIn']['password'].value;
if (uname.length || pword.length < 1 || '') {
var container = document.getElementById('error-container');
var errorMsg = document.createElement('div');
errorMsg.className = 'error-message';
errorMsg.innerHTML = '<span class="heading-large">Please enter a valid username or password</span>';
container.appendChild(errorMsg);
console.log('An error occured');
return false;
}
return true;
}
<form id="signIn">
<div class="boxed left-floater">
<h1 class="heading-large margin-top">Sign in</h1>
<div id="error-container"></div>
<div class="form-group">
<label class="form-label-bold" for="username">Username</label>
<input class="form-control log-in-form-control" id="username" name="username" type="text">
</div>
<div class="form-group">
<label class="form-label-bold" for="password">Password</label>
<input class="form-control log-in-form-control" id="password" type="password" name="password">
</div>
<div>
<a class="right-floater forgotten-password" href="forgottenpassword.html">Forgotten Password</a>
<button class="button clear right-floater" type="submit" onclick="validateMe(event);">Sign In</button>
</div>
</div>
</form>
I'm new to Javascript and I need to validate a log-in form with Bootstrap, the thing is not validating the password in the script.
https://jsfiddle.net/98uqsvu2/
<script type="text/javascript">
function check_info()
{
var user = document.getElementById("inputEmail").value;
var pass = document.getElementById("inputPassword").value;
if(user == "test#gmail.com")
{
if(pass == "123")
{
return true;
}
}
else
{
return false;
}
}
</script>
git: https://gist.github.com/Adaryn/6c38cfafd5e95d8a0bba508a33cebec7
#Adaryn
Since I cannot comment, I posted it as an answer.
I made the following changes to the fiddle and I was able to execute the code.
Removed the link href's from your HTML.
Added the closing body tag.
Moved the script from the javascript code section and pasted it just above the closing body tag.
Here is the updated fiddle.
<div class="container">
<form class="form-signin" form role="form" action="hola.html" name="formlogin" method="post" class="login-form" onsubmit="check_info()">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required="">
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<script type="text/javascript">
function check_info()
{
var user = document.getElementById("inputEmail").value;
var pass = document.getElementById("inputPassword").value;
if(user == "test#gmail.com")
{
if(pass == "123")
{
return true;
}
}
else
{
return false;
}
}
</script>
try this code. also added jsfiddle
document.getElementById("submit-form").addEventListener("click", check_info);
function check_info() {
var user = document.getElementById("inputEmail").value;
var pass = document.getElementById("inputPassword").value;
if (user == "test#gmail.com" && pass == "123") {
alert("email and password is valid!!!");
return true;
} else {
alert("email and password is NOT valid!!!");
return false;
}
}
https://jsfiddle.net/damaxrss/
I am trying to print the value from the form when a user submits the function but a blank value is returned.
Here is my JavaScript code:
var login = new function()
{
var name = null ;
this.validation = function()
{
this.name = document.getElementById("Username").value;
console.log(this.name);
document.getElementById("demo").innerHTML = this.name;
};
};
And my HTML form as :
<body>
<div class="container">
<div class="col-md-8">
<div class="starter-template">
<h1>Login with javascript</h1>
<p class="lead">Please Enter Following Details</p>
<h1 id="demo"></h1>
<form name="form" onSubmit="return login.validation();" action="#" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Username</label>
<input type="text" name="username" class="form-control" id="Username" placeholder="Please Enter your Username">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="Email" placeholder="Please enter your Password">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="Password" placeholder="Password">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Re-Password</label>
<input type="password" class="form-control" id="Re-Password" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
<script src="js/login.js"></script>
<script href="js/bootstrap.js"></script>
<!-- /.container -->
</body>
Why does the value not get into html <p> tag.
Your code simply works. But since the function executes on submitting the form, the username gets logged in the console fast before the page refreshed with submitted data. You can confirm this and test it by adding event.preventDefault(); to the function to prevent submitting the form so the page would stay visible with the console.
<script>
var login = new function()
{
var name = null ;
this.validation = function()
{
event.preventDefault();
this.name = document.getElementById("Username").value;
console.log(this.name);
document.getElementById("demo").innerHTML = this.name;
};
};
</script>
If that's not what you're looking for, let me know.
We the javascript validation failed you need to return false. If you don't it will proceed your form further. Thanks
var login = new function()
{
var name = null ;
this.validation = function()
{
this.name = document.getElementById("Username").value;
document.getElementById("demo").innerHTML = this.name;
return false;
};
};
I have tried many ways but when submit button is clicked it directly moves to next page without validating in client side through javascript. Please provide me the solution to this problem.
Here is the code:
function teacherValidateForm(){
var tuid=document.getElementById("tusername");
var tnme=document.getElementById("tname");
var tmail=document.getElementById("temail");
var tpsd=document.getElementById("tpssswod");
var tiname=document.getElementById("tiname");
function validateTID(tuid){
var message= "Username must start with a letter and must be of minimum 5 letters and '_' and '.' is allowed";
if((!tuid.match(/^[[A-Za-z][A-Za-z0-9/._]*]{5,}$/)) || tuid.value==""){
document.getElementById(uname).innerHTML=message;
return false;
}
else return true;
}
function validateTName(){
var message="Teacher's name muct not contain special characters and numbers";
if((!tnme.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/) || tnme.value==""){
document.getElementById(name).innerHTML=message;
return false;
}else return true;
}
function validateTEmail(){
var message="Enter a valid email";
if((!tmail.match(/^[A-Za-z\._\-0-9]*[#][A-Za-z]*[\.][a-z]{2,4}*$/) || tmail.value==""){
document.getElementById(email).innerHTML=message;
return false;
}else return true;
}
function validateTPass(){
var message="Password must contain special cahacters, one catital letter atleast and must be mininum 8 letters";
if((!tpsd.match(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[$#$!%*#?&])[A-Za-z\d$#$!%*#?&]{8,}$/) || tpsd.value==""){
document.getElementById(password).innerHTML=message;
return false;
}else return true;
}
function validateTName(){
var message="Institute's name muct not contain special characters and numbers";
if((!tiname.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/) || tnme.value==""){
document.getElementById(iname).innerHTML=message;
return false;
}else return true;
}
}
<body>
<div class="container-fluid" id="home">
<div class="text-center ">
<p></p><br/><br/><br/><br/>
<div class="container-fluid text-center">
<h4 style="font-family:sans-serif; color: #000; size: 60px; font-weight: bold">Registration form</h4></div>
</div>
<form name="teachersignup" class="form-horizontal" action="teacherLogin.jsp" method="POST">
<div class="form-group">
<label class="control-label col-md-4" style="color:#000; font-size:15px" >User Name: </label>
<div class="col-md-4">
<input type="text" class="form-control" id="tusername" /> <span class="error" id="uname"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4" style="color:#000; font-size:15px" >Teacher's Name: </label>
<div class="col-md-4">
<input type="text" class="form-control" id="tname" /> <span class="error" id="name" ></span>
</div>
</div>
<div class="form-group">
<label for="email" class="control-label col-md-4" style="color:#000; font-size:15px" >Email: </label>
<div class="col-md-4">
<input type="email" class="form-control" id="temail" /> <span class="error" id="email"></span>
</div>
</div>
<div class="form-group">
<label for="pswd" class="control-label col-md-4" style="color:#000; font-size:15px" >Password: </label>
<div class="col-md-4">
<input type="password" class="form-control" id="tpassword" /> <span class="error" id="password"></span>
</div>
</div>
<div class="form-group">
<label for="iname" class="control-label col-md-4" style="color:#000; font-size:15px" >Institute's Name: </label>
<div class="col-md-4">
<input type="text" class="form-control" id="tiname" /> <span class="error" id="iname"></span>
</div>
</div>
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-success" onsubmit="teacherValidateForm();">Submit</button>
</div>
</form>
</div>
</body>
You have several errors there. first you have to return value from the function in the html markup:
Firstly use <form name="teachersignup" class="form-horizontal" action="teacherLogin.jsp" method="POST" onsubmit="return teacherValidateForm();>
Then you can try the below function.Assuming that all your regular expressions are correct the below function should work just fine.
function teacherValidateForm()
{
var tuid=document.getElementById("tusername");
var tnme=document.getElementById("tname");
var tmail=document.getElementById("temail");
var tpsd=document.getElementById("tpssswod");
var tiname=document.getElementById("tiname");
if(!tuid.match(/^[[A-Za-z][A-Za-z0-9/._]*]{5,}$/) || tuid.value=="")
{
var message= "Username must start with a letter and must be of minimum 5 letters and '_' and '.' is allowed";
document.getElementById(uname).innerHTML=message;
return false;
}
if(!tnme.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/) || tnme.value=="")
{
var message="Teacher's name muct not contain special characters and numbers";
document.getElementById(name).innerHTML=message;
return false;
}
if(!tmail.match(/^[A-Za-z\._\-0-9]*[#][A-Za-z]*[\.][a-z]{2,4}*$/) || tmail.value=="")
{
var message="Enter a valid email";
document.getElementById(email).innerHTML=message;
return false;
}
if(!tpsd.match(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[$#$!%*#?&])[A-Za-z\d$#$!%*#?&]{8,}$/) || tpsd.value=="")
{
var message="Password must contain special cahacters, one catital letter atleast and must be mininum 8 letters";
document.getElementById(password).innerHTML=message;
return false;
}
if(!tiname.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/) || tnme.value=="")
{
var message="Institute's name muct not contain special characters and numbers";
document.getElementById(iname).innerHTML=message;
return false;
}
return true;
}
You are doing wrong.
var tuid=document.getElementById("tusername");
var tnme=document.getElementById("tname");
var tmail=document.getElementById("temail");
var tpsd=document.getElementById("tpssswod");
var tiname=document.getElementById("tiname");
Actually you are assigning those variable with the HTML input elements, but you need the values. So made some changes in these codes
var tuid=document.getElementById("tusername").value;
var tnme=document.getElementById("tname").value;
var tmail=document.getElementById("temail").value;
var tpsd=document.getElementById("tpssswod").value;
var tiname=document.getElementById("tiname").value;