if else loop issue - javascript

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);
}

Related

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.

Javascript - Login Box Not Working

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!');
}

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.

How to validate input using js and store the input in db

Javascript code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"></script>
<script type="text/javascript">
function validate()
{
var FirstName = document.getElementById('FN').value;
var LastName = document.getElementById('LN').value;
var Username = document.getElementById('userName').value;
var Email = document.getElementById('emailId').value;
var Password = document.getElementById('passWord').value;
if (FirstName == "")
{
alert("Please Enter First Name");
return false;
}
if (LastName == "")
{
alert("Please Enter Last Name");
return false;
}
if (Username == "")
{
alert("Username Should Not Contain Spaces");
return false;
}
if (Email == "")
{
alert("Please Enter Email");
return false;
}
if (Password == "")
{
alert("Password Should Not Contain Spaces");
return false;
}
var emailPat = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var EmailmatchArray = Email.match(emailPat);
if (EmailmatchArray == null)
{
alert("Your Email Address Seems Incorrect. Please Try Again.");
return false;
}
if(FirstName!== "" && LastName!=="" && Username!=="" && Email!=="" && Password!=="")
{
return true;
}
}
</script>
<form action="Registration" method="get">
FirstName : <input type="text" id="FN" name="FN"><br>
LastName : <input type="text" id="LN" name="LN"><br>
UserName : <input type="text" id="userName" name="userName"><br>
Password : <input type="password" id="passWord" name="passWord"><br>
Email : <input type="text" id="emailId" name="emailId"><br>
<input type="Submit" onclick="validate()">
Python code:
class Registration(View):
def get(self, request,msg):
user_name = request.GET['userName']
Firstname = request.GET['FN']
Lastname = request.GET['LN']
pass_word = request.GET['passWord']
email_id = request.GET['emailId']
db_results = usersCollection.find({"userName": user_name})
print db_results
print db_results.count()
print user_name
print dumps(db_results)
if db_results.count() == 0:
token = binascii.b2a_hex(os.urandom(25))
#encrypting password...
encrypted_password = pwd_context.encrypt(pass_word)
database_key = usersCollection.insert(
{"Firstname":Firstname, "Lastname":Lastname, "userName": user_name, "passWord": encrypted_password, "emailId": email_id, "token": token,
"status": 0, "isSuperUser": "No", "forgotPasswordToken": '',
"createdOn": datetime.datetime.now()})
if database_key != '':
return_output = {'message': 'Signup completed successfully! ', 'status': 'success'}
return HttpResponse(dumps(return_output))
HI friends I want to validate the input using javascript and if all the fields are correct then i want to store them in db I have put the code to do that but when i submit the form without input am getting only one alert message and then after closing the alert am getting a message written in python code and the empty input is stored in db please help where am i doing wrong.........
Basically what is happening is that your form is getting submitted anyway, irrespective of the return value of the function.
So instead of calling the validate() function on click, call in onsubmit. like this-
<form action="Registration" method="get" onsubmit="return validate();">
and remove the onclick event.
When false is returned from validate(), the form will not be sent.

Single else clause for multiple if clauses - javascript

First: I'm JavaScript newbie.
So.. I have basic form with password, repeat password, email and repeat email fields. I want to check if password is equal to repeat password. If it's not, alert message appears and page reloads. Same for email and repeat email.
BUT if pass and repeat password aren't equal AND email and repeat email aren't equal, first alert message appears, then the second message (this time for email) appears too fast. I want to show only one alert message when both fields don't match.
<script type="text/javascript">
function checkFields() {
var pass= document.getElementById('password');
var reppass= document.getElementById('reppass');
var email= document.getElementById('email');
var repemail= document.getElementById('repemail');
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
}
else if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
}
</script>
And the form:
<form onSubmit="checkFields()">
<p><label>Password:</label> <input name="password" id="password" required="true" type="password" /></p>
<p><label>Repeat password:</label> <input name="reppass" id="reppass" required="true" type="password" /></p>
<p><label>Email:</label> <input name="email" id="email" required="true" type="email" /></p>
<p><label>Repeat Email:</label> <input name="repemail" id="repemail" required="true" type="email" /></p>
<p><input type="submit" value="Send"></p>
</form>
You can simply return from the if clauses like this:
function checkFields() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
return;
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
return;
}
}
I like this style, because it prevents nesting if clauses. The downside is, that you have multiple return points that can be confusing - this heavily depends on the length of the function.
EDIT
Updated order of if blocks
if( condition1 ) {
}else if( condition2 ) {
}else{
…
}
I believe this is what you want.
One solution would be to break the validation up into separate methods, then only run the second validation if the first one succeeds.
Here's an example:
var FormValiditor = function() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
return {
checkFields: function() {
if(checkPassword()){
return checkEmail();
}
return false;
},
checkPassword: function() {
if (pass.value != reppass.value) {
alert("Password don't match");
return false;
}
return true;
},
checkEmail: function() {
if(email.value != repemail.value){
alert("Emails do not match");
return false
}
return true
}
}
}();
Then, if you're using jQuery(which you should be!) you can run validation when the form gets submitted.
$('form').submit(FormValidator.checkFields);
if ...
else if ...
else if ...
...
else ...
That's how it should be structured. You can have as many else ifs as you like.

Categories

Resources