Question about login function with CryptoJS? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 days ago.
Improve this question
I am new to javascript. I am working on a login form with CryptoJS. I have three functions in total. They are onsubmit function, checkLogin function and encrytion function. I have to use the onsubmit function to call the checkLogin function to validate user input but I don't know how to do so. Besides, I have to use the encrytion function to turn user input to another string, then use the checkLogin function to call the encryption function and get the string. The checkLogin function and encryption function should not directly access DOM. Finally both functions will be used for Jasmine testing but I don't need to do it right now. I just want to make my form works normally. I don't know how to exactly modify my onsubmit function and checkLogin function to make it works.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Login Page</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
<script src="Jasmine/lib/md5.js"></script>
</head>
<body>
<header>
<h1>Login Page</h1>
</header>
<section id="form" class="form">
<form name="submitForm" action="#" method="POST">
<fieldset class="form__field">
<legend>User Authentication</legend>
<p><label for="in_username" class="form__username" >Username:</label>
<input type="text" name="username" id="in_username"/></p>
<p><label for="in_password" class="form__password">Password:</label>
<input type="password" name="password" id="in_password"/></p>
<input type="submit" value="Log in" class="form__submit" />
</fieldset>
</form>
</section>
<!-- output message -->
<section id="output" class="output">
</section>
</body>
</html>
Encryption function is confirmed to be ok.
function md5Encrypt(stringIn) {
"use strict";
var md5string = new CryptoJS.MD5(stringIn);
return md5string.toString();
}
What I want to do is to output the result in the same page and this is my current code.
How to use checkLogin function to call encryption function and return true when username is abc and password is 123123? After I output a variable, how do I use the onsubmit function to take the variable? Thank you!
window.onload = function () {
"use strict";
var myLogin = document.forms.submitForm;
var myMessage = document.getElementById("output");
myMessage.classList.add("displaynone");
myLogin.onsubmit = processForm;
function processForm() {
var inName = document.getElementById("in_username");
var inPassword = document.getElementById("in_password");
checkLogin(inName, inPassword);
myMessage.classList.add("displayblock");
myMessage.innerHTML = output;
return false;
}
function checkLogin(inName, inPassword){
var myName = "abc";
var myPassword = "123123";
var output = "";
var noName = "No username entered";
var noPassword = "No password entered"
var valid = "Welcome back!";
var invalid = "Invalid Username or Password";
if(inName.value(myName) && inPassword.value(myPassword)){
output = valid;
} else if (inName.value("")){
output = noName;
} else if(inPassword.value("")){
output = noPassword;
} else {
output = invalid;
}
return output;
}
};

Related

if else loop not executing it's false condition? [duplicate]

This question already has answers here:
Javascript's .includes function not working correctly with array of objects [duplicate]
(2 answers)
How to determine if Javascript array contains an object with an attribute that equals a given value?
(27 answers)
Closed 4 months ago.
I'm trying to make an online library arrary that gets inputs for the value of a "book" object from a user form.
The problem is I made an if function to check if the currently submitted inputs match an already existing "book" object. Yet the function passes every input I make no matter if it's exactly the same.
Here is the Js
const submit = document.getElementById("submit");
const cardbox = document.getElementById("cardBox");
class Library {
constructor() {
this.books = [];
}
}
const myLibrary = new Library();
class Book {
constructor(title, author, pageCount, haveRead) {
this.title = title;
this.author = author;
this.pageCount = pageCount;
this.haveRead = haveRead;
}
}
function getBook() {
const book = new Book();
book.title = document.getElementById('title').value
book.author = document.getElementById('author').value
book.pageCount = document.getElementById('pageCount').value
book.haveRead = document.getElementById('haveRead').checked
function addBook() {
if (!myLibrary.books.includes(book)) {
myLibrary.books.push(book);
return makeCard(book);
}
else {
alert("Error: This book is already in library, pls reload and try again");
stop();
}
}
function makeCard() {
const card = document.createElement("div");
const titleCard = document.createElement("p");
const authorCard = document.createElement("p");
const pageCountCard = document.createElement("p");
titleCard.textContent = "Title: " + book.title;
authorCard.textContent = "Author: " + book.author;
pageCountCard.textContent = "Page Count: " + book.pageCount;
card.style.backgroundColor = "red";
card.style.fontSize = "20px"
cardbox.style.display = "flex"
card.appendChild(titleCard);
card.appendChild(authorCard);
card.appendChild(pageCountCard);
cardbox.appendChild(card);
return card;
}
addBook(book);
return book;
}
submit.addEventListener("click", function() {
getBook();
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="entry">
<form action="#" method="post">
<label for="title">Book title:</label>
<input type="text" id="title" name="book title" placeholder="insert book title here"><br>
<label for="author">Author:</label>
<input type="text" id="author" name="book author" placeholder="insert book author here"><br>
<label for="pageCount">How many pages is it?</label>
<input type="text" id="pageCount" name="pageCount" placeholder="insert page count here"><br>
<label for="read">Have you read already?</label>
<input type="checkbox" id="haveRead" name="read" placeholder="insert read status here">
</form>
<button type="submit" id="submit">Submit</button>
<div id="cardBox"></div>
</div>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
And there is the HTML for good measure. What am I missing here?

Console log data return as null

Sorry for the little explanation. So i have already done my chrome extension and i already have a save data in my localstorage which is FirstName. so now the getElementById is the one suppose to web scape my current page that i am on to fill up the form when i click START which is button1 Hopefully these clear things
i have also provided my index.html where if i click start it should execute injector.js
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<style>
html,
body {
height: 200px;
width: 400px;
}
</style>
</head>
<body>
<h1>Adidas ACO</h1>
<h2>Select your choice</h2>
<button>Go for Setup</button>
<button id="buttonstart"><script src="injector.js"></script>
</script>START</button>
<!-- <br>
<br>
<label for="Title">Title</label>
<input type="text" id="firstnametitle" name="title" size="50" value=""/> -->
<!--<script scr="injector.js"></script>-->
<!--<button onclick="fillforms(fillup)">Start</button>-->
</body>
</html>
injector.js
// Get my button and localstorage data
var button1 = document.getElementById("buttonstart");
var firstName = localStorage.getItem('First Name');
var lastName = localStorage.getItem('Last Name');
var address1 = localStorage.getItem('Address 1');
var address2 = localStorage.getItem('Address 2');
var email = localStorage.getItem('Email');
var phoneNumber = localStorage.getItem('Phone Number');
/// When button is click, it will webscape and fill up
button1.onclick = function(){
var firstName = localStorage.getItem('First Name');
var field1 = document.getElementsByClassName("shippingAddress-firstName");
fillField(field1, firstName);
console.log(field1)
console.log(firstName)
}
function fillField(field1, value){
if(field1){
field1.value = value;
}
}
Picture to my console values
Declare the variables firstname and field1 at the start of the file.You have to do it because in your code you can only use those variables inside the button1.onclick function since you have declared them there.

How to fix the logic problem in my loop for my basic logon screen

I get the code to tell me when someone types in a bad userid or password. And I can get it to let people in when the get they type in the first userid and password
user1 and pass1
But, if they try user2 and pass2 it says it is a wrong password. I know it is a logic error on my part with the loop, but, cant figure it out for the life of me! Please help me understand if you guys can!
Thank you
<!DOCTYPE html>
<html lang="en">
<head>
<title>Assignment 1</title>
<link rel="stylesheet" type="text/css" href="css/login.css">
</head>
<body>
<script>
document.body.style.backgroundColor = "grey";
var valid = false;
function validate() {
var useArray = ["user1", "user2", "user3"];
var passArray = ["pass1", "pass2", "pass3"];
var x = document.login.userId.value;
var y = document.login.passWord.value;
for(var i = 0; i < useArray.length; i++) {
if (x == useArray[i] && y == passArray[i]) {
document.write("You have successfully logged on to your
class!");
return false;
} else if (i = useArray.length - 1) {
document.write("Error: User Id is not valid, please click the
link below again \n \n");
var l =(" link back");
var back = l.link("practice.html");
document.write(back);
return false;
}
}
}
</script>
<div class="container">
<h1>Logon</h1>
<form name="login">
<label for="useId">Userid: </label>
<input type="text" name="userId" required>
<br><br>
<label for="passWord">Password: </label>
<input type="password" name="passWord" required>
<br><br>
<input type="button" class="submit" value="Log In" name="submit"
onclick="validate(this.form)">
</form>
</div>
<br><br>
</body>
</html>
I need it to accept the other parts of the Array too. When someone puts in usee2 and pass2 for example
Thank you
You're having trouble over here else if (i = useArray.length - 1)
useArray.length is going to be 3 for all loops so userArray.length - 1 will always eval to 2, you're setting i = 2 inside the if
in JS the assignment operator also returns the value assigned so you're basically writing
else if( 2 ) which will always evaluate to true

Javascript " onsubmit " Event Not Working Correctly

I am just practicing js. I am trying to make a very simple validation in form but it came with, as i was expecting, an error.
Here's my code :
var form = document.getElementById('form');
var name = document.getElementById('name');
var email = document.getElementById('email');
var msg = document.getElementById('message');
var error = document.getElementById('error');
function handlingForm() {
form.onsubmit = function(c)
{
if (name.value == "")
{
error.innerHTML = "Error Submiting Form !";
return false;
}
else
{
error.innerHTML = "You have successfuly submited the Form..! Congrats ;)";
return true; // ;) Just Kidding :D
}
};
}
window.onload = function(c)
{
handlingForm();
}
<!DOCTYPE html>
<html>
<head>
<title>jsForm</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<form id="form">
<input type="text" placeholder="Name" id="name">
<input type="text" placeholder="Email" id="email">
<textarea rows="4" placeholder="Message" id="message"></textarea>
<input type="submit" value="Send" id="send">
<p id="error"></p>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
The problem is that, it doesn't validate it. Every time it returns true on submitting but when i replace the " name.value" with "email.value" the code works. I don't know now what's the problem actually. If someone could help me..
It looks like the input with id name is not created in DOM by the time of JavaScript execution.
You can resolve that by putting the code in the window.onload code block or inside the form.onsubmit
var form = document.getElementById('form');
var email = document.getElementById('email');
var msg = document.getElementById('message');
var error = document.getElementById('error');
function handlingForm() {
form.onsubmit = function(c) {
var name = document.getElementById('name');
if (name.value == "") {
error.innerHTML = "Error Submiting Form !";
return false;
} else {
error.innerHTML = "You have successfuly submited the Form..! Congrats ;)";
return true; // ;) Just Kidding :D
}
};
};
handlingForm();
<div id="container">
<form id="form">
<input type="text" placeholder="Name" id="name">
<input type="text" placeholder="Email" id="email">
<textarea rows="4" placeholder="Message" id="message"></textarea>
<input type="submit" value="Send" id="send">
<p id="error"></p>
</form>
</div>
Your variable called name is a problem. It's not working because name is a predefined identifier in some implementations. Though it's not a reserved keyword, it's best practice to avoid using it as a variable name.
Rename it to name_ (or almost anything else) and it will work.
If name.value has no value, it is undefined. So undefined !== "", which is why it will never be true. Just do a null check for name.value. Also, you need to move name inside of that function since the first time it is called, value will always be undefined:
var form = document.getElementById('form');
var email = document.getElementById('email');
var msg = document.getElementById('message');
var error = document.getElementById('error');
function handlingForm() {
form.onsubmit = function(c)
{
var name = document.getElementById('name');
if (!name.value)
{
error.innerHTML = "Error Submiting Form !";
return false;
}
else
{
error.innerHTML = "You have successfuly submited the Form..! Congrats ;)";
return true; // ;) Just Kidding :D
}
};
}
window.onload = function(c)
{
handlingForm();
}
<!DOCTYPE html>
<html>
<head>
<title>jsForm</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<form id="form">
<input type="text" placeholder="Name" id="name">
<input type="text" placeholder="Email" id="email">
<textarea rows="4" placeholder="Message" id="message"></textarea>
<input type="submit" value="Send" id="send">
<p id="error"></p>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
Try this:
window.onload = handlingForm();
Why your function has c parameter?
This is due to a quirk of how global variables are handled in web pages. Each one is treated as a property of the window object, so when you assign to email, you're actually creating and assigning to window.email, and so on.
However, some properties of the window object already exist and have special meaning to the browser, such as window.location (the current URL) and window.name (used in cross-frame link targets).
To see it in practice, do this in the global scope (outside any function):
var location; // should be undefined, right?
alert(location); // but it's actually window.location
Because of the special meaning of window.name, anything you assign to it (or to global name) will be converted into a string. The element that you try to store becomes a string, and so no longer works as an element.
To fix it, simply move your code into a function, so that the variables are local and no longer have this strange behaviour. You can use your window.onload function for this.

javascript form validation object

Please i just started learning javascript, In order to build my skill. I gave myself a javascript project to build an object validator.The first method i created is checkEmpty. This method check for empty field. But for reason unknow to me the method don't work.
This is the html form
<form name="myForm">
<input type="text" class="required email" name='fName'/>
<input type="text" class="required number" name="lName"/>
<input type="submit" value="submit" name="submit" id="submit"/>
</form>
This is the javascript that called the validator object
window.onload = function(){
var validate = new FormValidator('myForm');
var submit = document.getElementById('submit');
//this method won't work for internet explorer
submit.addEventListener('click',function(){return checkLogic();},false);
var checkLogic = function(){
validate.checkEmpty('fName');
};
}
This is the javascript object called Formvalidation
function FormValidator(myForm){
//check ur error in stack overflow;
this.myForm = document.myForm;
this.error = '';
if(typeof this.myForm === 'undefined'){
alert('u did not give the form name ');
return;
}
}
//this method will check wheather a field is empty or not
FormValidator.prototype.checkEmpty = function(oEmpty){
var oEmpty = this.myForm.oEmpty;
if(oEmpty.value === '' || oEmpty.value.length === 0){
this.error += "Please Enter a valid Error Message \n";
}
FormValidator.printError(this.error);
};
This method printout the error;
FormValidator.printError = function(oData){
alert(oData);
};
After formatting your code it got a lot easier to find out what went wrong. I assume you are trying to validate the input fields from your html code.
Your code is falling on its nose the first time in line 1 of the method checkEmpty():
FormValidator.prototype.checkEmpty = function(oEmpty){
var oEmpty = this.myForm.oEmpty;
if(oEmpty.value === '' || oEmpty.value.length === 0){
this.error += "Please Enter a valid Error Message \n";
}
FormValidator.printError(this.error);
};
In the first line you are hiding the methods argument oEmpty with the var oEmpty statement from line 1
There are several other issues like overusing methods and members. The following code is probably what you wanted:
1.) index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<form name="myForm">
<input id="fName" name='fName' type="text"/>
<input id="lName" name="lName" type="text"/>
<input id="submit" name="submit" type="submit" value="submit"/>
</form>
<script src="main.js"></script>
</body>
</html>
2.) main.js
function InputFieldValidator(inputFieldName){
this.inputFieldName = inputFieldName;
this.inputField = document.getElementById(this.inputFieldName);
if(this.inputField === 'undefined'){
alert('No input field: ' + this.inputFieldName);
}
}
InputFieldValidator.prototype.validate = function(){
if(this.inputField.value === ''){
alert('Please enter valid text for input field: ' + this.inputFieldName);
}
};
window.onload = function(){
var fNameValidator = new InputFieldValidator('fName'),
lNameValidator = new InputFieldValidator('lName'),
submitButton = document.getElementById('submit');
submitButton.addEventListener('click', function (){
fNameValidator.validate();
lNameValidator.validate();
});
};
If you like you can wrap the input field validators from above easily in a form validator.
This is the right way to define functions this way:
var FormValidator = function(myForm){ /* function body */ };
FormValidator.prototype.checkEmpty = function(oEmpty){ /* function body */ };
Than, after instantiating the object, you can call FormValidator.checkEmpty(value) like you did.

Categories