Javascript - Login Box Not Working - javascript

I am currently making a javascript and html mini-login box. I have created a javascript code which checks the length of the password and checks if confirm password and password are the same. Here is the code...
<form name = "logme">
<fieldset>
<legend>Create Your Account!</legend>
<br>
<p>Username:*<input type="text" name="user" placeholder="Enter Your Name">
<br>
<br>
Password:*<input type="password" id="pass">
<br>
<p>Confirm Password:*<input type="password" id="passwd">
<br>
<p>Email:*<input type="text" id="email" placeholder="you#example.com">
<br>
<br>
Show Password:<input id="chk" name="chk" type="checkbox" onclick="validate()" />
<br>
<br>
<input type="button" value="Create!" name="Submit" onclick="pwFunction()">
</p>
Don't Have An Account? Create One!
</fieldset>
</form>
<script>
function pwFunction() {
var password = document.getElementById('pass');
var lok = password.value.length >= 8;
var cpassword = document.getElementById('passwd');
if (!lok) {
alert('Your Password Must Have Eight Characters!');
}
return lok;
if(password.value != cpassword.value) {
alert('Your Passwords Do Not Match!');
}
}
</script>
It Only Runs The 'Your Password Must Have Eight Characters' Alert.
Why Isn't It Running Both?
Thanks For Any Answers, And Sorry For The Inconvenience.

There are a couple of error in your code / scripts:
Edit 1. Change the button to
<input type="submit" value="Create!" name="Submit" >
Edit 2. Use javascript validation on form tag
<form name = "logme" action="somewhere" onsubmit = "return pwFunction();">
This way the form is submitted only when the pwFunction() returns true.
Edit 3. Your javascript function should be:
function pwFunction() {
var password = document.getElementById('pass');
var cpassword = document.getElementById('passwd');
if (password.value.length < 8) {
alert('Your Password Must Have Eight Characters!');
return false;
}
if(password.value != cpassword.value) {
alert('Your Passwords Do Not Match!');
return false;
}
else
{
return true;
}
}

Try
if(password.value !== cpassword.value) {
alert('Your Passwords Do Not Match!');
}

Like you did, the return statement is executed always, so it causes the function to stop execution and return a result. delete the return statement:
if (!lok) {
alert('Your Password Must Have Eight Characters!');
}
if(password.value != cpassword.value) {
alert('Your Passwords Do Not Match!');
}

Related

Trying to validate username and password in javascript but not getting alert and desired output

please check the code
function validate() {
var name = document.getElementById("name");
var pwd = document.getElementById("pwd");
if (name == null || name == "") {
alert("Name can't be blank");
return false;
} else if (pwd.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
<form>
username: <input type="text" id="name"></input>
<br>
password: <input type="password" id="pwd"></input>
<br>
<button onclick="validate()">Submit</button>
</form>
function validate() {
var name = document.getElementById("name").value;
var pwd = document.getElementById("pwd").value;
if (name === null || name === "") {
alert("Name can't be blank");
return false;
} else if (pwd.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
<form>
username: <input type="text" id="name"></input>
<br>
password: <input type="password" id="pwd"></input>
<br>
<button onclick="validate()">Submit</button>
</form>
There's a much easier way to do what you are trying to do. You can use the native properties of form to your advantage:
<form>
Username: <input type="text" minlength="2" required>
<br> Password: <input type="password" minlength="6" required>
<br>
<button type="submit">Submit</button>
</form>
HTML elements should be before javascript, like this:
<!DOCTYPE html>
<html>
<body>
<form>
username: <input type="text" id="name"></input>
<br>
password: <input type="password" id="pwd"></input>
<br>
<button onclick="validate()">Submit</button>
</form>
<script>
function validate() {
var name = document.getElementById("name").value;
var pwd = document.getElementById("pwd").value;
if (name == null || name == "") {
alert("Name can't be blank");
return false;
} else if (pwd.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
</body>
</html>
You haven't provided the full code, so we can't really help you. As far as i can see you didn't make the alert for succesful validation.
You need to get the value, so you need to add .value to the getElement functions.

How to make it run through the 3 validations before being able to send the form action to an address

My code currently validates that the name/email and postcode is valid before being able to send when there is NO address that the information is meant to go to in the form action ="". But when I put the address it's meant to go to it completely skips the validation and just sends whatever, empty or not empty.
Trying to re-position the form action, but really have no idea.
<html>
<head>
<title>Online Food Delivery Form</title>
<h1>Online Food Delivery Form</h1>
</head>
<body>
<form action="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi"
method="get" onsubmit="return validation();">
Name* : <input type="text" name="name" id="name">
<br />
<br />
Email* : <input type="email" name="email" id="email">
<br />
<br />
Postcode* : <input type="text" name="postcode" id="postcode" size="10">
<input type="reset" value="Reset"></button>
<input type="submit" name="submit" value="Submit"/>
</form>
<div id="eresult" style="color:red;"></div>
<script type="text/javascript">
function validation(){
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var postcode = document.getElementById('postcode').value;
if(name=='' || postcode=='' || email==''){
document.getElementById("eresult").innerHTML = "Name, Email and Postcode
are required.";
return false;
}
else if(name.length<3){
document.getElementById("eresult").innerHTML = "Name must be more than 3
characters.";
return false;
}
else if(postcode.length<4){
document.getElementById("eresult").innerHTML = "Postcode must be atleast
4 characters.";
return false;
}
else {
return true;
}
}
</script>
</body>
</html>
Expected results is for the code to validate that the email/name and postcode is correct before sending the information to the designated site. But it's doing complete opposite.
In your validation, your error messages are multi-line strings
if(name=='' || postcode=='' || email==''){
document.getElementById("eresult").innerHTML = "Name, Email and Postcode
are required.";
return false;
}
else if(name.length<3){
document.getElementById("eresult").innerHTML = "Name must be more than 3
characters.";
return false;
}
else if(postcode.length<4){
document.getElementById("eresult").innerHTML = "Postcode must be atleast
4 characters.";
return false;
}
If you open up the developer console (usually F12), you'll see an error caused by an Invalid or Unexpected Token. Change these error messages to fit on one line to fix this error:
if(name=='' || postcode=='' || email==''){
document.getElementById("eresult").innerHTML = "Name, Email and Postcode are required.";
return false;
}
else if(name.length<3){
document.getElementById("eresult").innerHTML = "Name must be more than 3 characters.";
return false;
}
else if(postcode.length<4){
document.getElementById("eresult").innerHTML = "Postcode must be atleast 4 characters.";
return false;
}
Also, you have a closing </button> tag but no opening one! Remove that tag from the line <input type="reset" value="Reset"></button>.
Hope this helps!

Text obtained with innerHTML dissapear

I have the following code:
function passVerif() {
if (document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
if (document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="button" name="required" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
As you can see, input type is submit. Because of that (page is refreshing after click on button) the text I want to show disappears after refresh.
As I read on other posts, the simple change from submit to button will do the dew.
But I am suspecting that I messed up the return false and return true instructions in all of my functions.
Is this correct? If they are in a logical way I can avoid the page refresh and continue to use submit? At least until all conditions are met and the form is good to go.
In other words, can someone help me to put return false and true in such way that the page will refresh only if all conditions are met.
Thanks a lot, I am not even a noob.
Codes are copied from different sources on the internet. I am at the very beginning of coding road. Please have mercy :)
I would change it to one validation function and have a bool that is returned based on if it has errored or not:
// Just have one validation function
function validate() {
var errorMessage = ''; // build up an error message
var email = document.forms['form'].email.value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (email === "") {
errorMessage += "Email field is empty!<br>";
} else if (!emailFilter.test(email)) { // this can be else if
errorMessage += "Please enter a valid e-mail address!<br>";
}
if (document.forms['form'].pass.value === "") {
errorMessage += "Password field is empty!<br>"
}
if (errorMessage === '') {
return true; // return true as no error message
} else {
document.getElementById('error-message').innerHTML = errorMessage; // show error message and return false
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="submit" name="required" onclick="return validate();">
</form>
</div>
<div id="error-message">
<!-- CAN HAVE ONE ERROR MESSAGE DIV -->
</div>
I tried with your code and I could find the the messages were not getting updated based on the conditions. So I did few modifications to your code to display the message based on which condition fails.
HTML
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br><br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br><br>
<input type="submit" name="required" value="Submit" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
JS
function passVerif() {
messagePV.innerHTML = ("")
if(document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
messageEV.innerHTML = ("")
if(document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
messageV.innerHTML = ("")
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
By initializing the errormessage filed to empty sting u can maintain the fresh set of error messages.
Jsfiddle: https://jsfiddle.net/85w7qaqx/1/
Hope this helps out.

if else loop issue

I've been working on a login form which I've been trying to wrap my head around. Essentially, the if() statement isn't doing what I expect. Even if the core.user/core.pass exactly match the set values, it's not getting to the success case.
function validateLoginForm()
{
//var x = document.forms["myForm"]["username"].value;
//var y = document.forms["myForm"]["password"].value;
"use strict";
var username = document.forms["myForm"]["username"].value;
var password = document.forms["myForm"]["password"].value;
console.log("username:" + username);
console.log("password:" + password);
var coreUser = "testUser";
var corePass = "testPass";
if (username.value === coreUser) {
console.log("username matches");
if(password.value === corePass) {
console.log("You are logged in as " + username.value);
}
else {
alert("Password invalid");
}
}
else {
alert("Username invalid");
}
}
<div class="loginPage">
<div name="myForm" class="form">
<div id ="login">
<form class="login-form" name="myForm">
<h2>Login Page</h2>
<input name="username" id="username" type="text" placeholder="enter username"/>
<input name="password" id="password" type="password" placeholder="enter password"/>
<button type="button" onclick="validateLoginForm()">login</button>
<p class="message">Don't have an account? Register</p>
</form>
</div>
</div>
</div>
password and username already contains the value. So you are trying to call .value on a string which returns undefined. Just remove the .value when you are using the password and username variables like this.
if (username === coreUser) {
//...
if(password === corePass) {
//...
Also, this kind of bug is easilly found with a debugger. You should take the time to learn how to use one as it will save you considerable time in the future. (every modern browser have a JS debugger in the dev tool)
You just remove .value from username.value & password.value
user like in below
username === coreUser
password === corePass
In javascript validation we should have return statement if the value is invalid.
for example :
if(username !== coreUser || username ==='') {
alert("Username invalid");
return false;
} else if(password !== corePass || password === '') {
alert("Password invalid");
return false;
} else {
console.log("username matches");
console.log("You are logged in as " + username);
}

How come my JavaScript isn't working?

I am doing a login page for school. I have written the page, but the JavaScript does not seem to work with the form. I have checked over both the form and the JavaScript multiple times, but I see no mistake. Can anyone help me?
function processInfo() {
var theusername;
var thepassword;
theusername = document.myForm.username.value;
thepassword = document.myForm.password.value;
if (document.myForm.username.value = "") {
alert("Please enter in the username.")
return false;
} else if (document.myForm.password = "") {
alert("Please enter in the password.")
return false;
} else if (document.myForm.username.value != "andrew123") {
document.myForm.txtOutput.value = "Incorrect username or password."
} else if (thepassword != "abc") {
document.myForm.txtOutput.value = "Incorrect username or password."
} else if (theusername == "andrew123"
thepassword == "abc") {
document.myForm.txtOutput.value = "Correct! You have successfully logged in."
}
}
<form name="myForm">
<b>User Name:</b>
<input type="text" name="username" size="36" maxlength="100">
<b>Password:</b>
<input type="text" name="password" size="36" maxlength="100">
<p>
<input type=button value="VERIFY INFORMATION" onClick=processInfo()>
</p>
<textarea name="txtOutput" rows=1 cols=4 0></textarea>
</form>
= is an assignment, you keep using it when you are trying to perform a comparison (which would use == or ===).
Sometimes you try to compare the form control with a string instead of getting its .value.
You forgot to put a boolean AND between the two conditions you have theusername == "andrew123"
thepassword == "abc"
You should learn to use the console in your browser as most of these problems would be highlighted in it or could be with the addition of a little logging.

Categories

Resources