So I wanted to make a kind of admin login in js so I put two conditionals in the if and else if. I also used arrays to minimize the line of code needed. But it is always running the else block no matter what. I tried putting === instead of == but still not working.
Here's the Edit EDIT js code:
var avatar = document.getElementById('pfic');
var admin = ['jonh.josh#gmail.com', 'Jonh Josh', '123456'];
var admin2 = ['sam.jackson#gmail.com', 'Sam Jackson', 'abcdefg'];
var access = "no";
var user = document.getElementById('email_input').value;
var code = document.getElementById('password_input').value;
document.querySelector('button').onclick = function () {
if (user == admin[0] && code == admin[2]) {
avatar.setAttribute('src', 'images/ganiavatar.png');
access = "yes";
} else if (user == admin2[0] && code == admin2[2]) {
avatar.setAttribute('src', 'images/kanatavatar.png');
access = "yes";
} else {
alert("Please make sure you entered the correct creditionals");
access = "no";
}
And here is the part of html code:
<image scr="images/defult_profile.jpg" alt="defult profile picture" id="pfic">
<input class="input1 input" id="email_input" placeholder=" Phone# / Email"></input>
<input class="input2 input" id="password_input" type="password" placeholder=" Password"></input>
You're reading the values for user and code when the page loads, not when the button is clicked. Therefore they'll always be empty strings.
var user = document.getElementById('email_input').value;
var code = document.getElementById('password_input').value;
To fix the issue, move the above lines inside the button click event handler.
document.querySelector('button').onclick = function () {
var user = document.getElementById('email_input').value;
var code = document.getElementById('password_input').value;
if (user == admin[0] && code == admin[2]) {
avatar.setAttribute('src', 'images/ganiavatar.png');
access = "yes";
} else if (user == admin2[0] && code == admin2[2]) {
avatar.setAttribute('src', 'images/kanatavatar.png');
access = "yes";
} else {
alert("Please make sure you entered the correct creditionals");
access = "no";
}
}
And if you're not already aware, implementing authentication on the client-side will provide zero protection and is easily bypassed, since the source code is publicly accessible.
Related
I'm sure I'm missing something obvious here but I've had a really good look over this, combing for typos and such but I can't see what the problem is. I want this to be a simple form that requires a username/password combination to validate. The usernames/passwords having to match hasn't been implemented yet because my initial testing can't get over this first hurdle of the form always validating!
I've definitely made a solid go at it and I feel bad I'm getting stuck here, even looking over tons of references and comparing them to my own. I'm not even sure if the event listener itself is the problem or if the problem comes from poor coding in the function. Opening console in browser shows me no errors either. Could anybody point out where my issue is? Thanks.
"use strict";
let loginform = document.forms.login;
loginform.addEventListener("submit", checkLogin);
let users = [];
let pwords = [];
users = ["Administrator", "Manager", "Cleric", "Scribe"];
pwords = ["Password01", "Password", "Admin", "P#ssword"];
//*** NOTE: the password for each username is specific. Use the the alignment of the data in the table above (i.e. the password for the Administrator account is Password01, etc.). ***
function checkLogin() {
var usernameInput = loginform.getElementById("Username").value;
var pwInput = loginform.getElementById("Password").value;
//.includes is what we need for the array checking if statements
//For Loop 1
for (usernameInput in users) {
if (!users.includes(usernameInput)) {
window.event.preventDefault();
alert("Your username is incorrect. Please try again.")
loginform.user.focus();
return false;
} else {
//For Loop 2
for (pwInput in pwords) {
if (!pwords.includes(pwInput)) {
window.event.preventDefault();
alert("Your password is incorrect. Please try again.")
loginform.pword.focus();
return false;
}
}
}
}
}
<h1 id="main">Login to Umbrella Corporation</h1>
<div id="container">
<form name="login" action="success.html" method="POST">
<input type="text" name="user" id="Username">
<br>
<br>
<input type="password" name="pword" id="Password">
<br>
<br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</div>
The form element does not have a getElementById.
Change to one of these
var usernameInput = loginform.user.value;
var pwInput = loginform.pword.value;
var usernameInput = loginform.querySelector("#Username").value;
var pwInput = loginform.querySelector("#Password").value;
var usernameInput = document.getElementById("Username").value;
var pwInput = document.getElementById("Password").value;
You do NOT need to loop and then use includes
if (!users.includes(usernameInput))
is enough
Here is an optimised test
function checkLogin(e) { // event is available here
const usernameInput = loginform.user.value;
const pwInput = loginform.pword.value;
if (!users.includes(usernameInput)) {
e.preventDefault();
alert("Your username is incorrect. Please try again.")
loginform.user.focus();
return false;
} / no need for else after a return
if (!pwords.includes(pwInput)) {
e.preventDefault();
alert("Your password is incorrect. Please try again.")
loginform.pword.focus();
}
}
I think the problem here is that you're trying to loop through your data using the input provided:
var usernameInput = loginform.getElementById("Username").value;
for (usernameInput in users) {...}
This won't work. What you can do is find if the username that the user has provided is present in the array.
var usernameInput = loginform.getElementById("Username").value;
const userIndex = users.indexOf(usernameInput);
If a user is found, it will return a valid index, else it'll return a -1. You can use this to throw an error to the user.
You can do the same with the password:
var pwInput = loginform.getElementById("Password").value;
const pwIndex = pwords.indexOf(pwInput);
At the final check, you can compare the two indices. If they are equal, they are the right combo, else it's an incorrect username/password combo.
if(pwIndex === userIndex && pwIndex !== -1){...} // Success
else {...} // Failure
Finally, this is how your JavaScript should look like:
function checkLogin() {
var usernameInput = loginform.getElementById("Username").value;
var pwInput = loginform.getElementById("Password").value;
//.includes is what we need for the array checking if statements
const userIndex = users.indexOf(usernameInput);
const pwIndex = pwords.indexOf(pwInput);
if(userIndex === -1 || pwIndex === -1) {
alert("Your username/password is incorrect"); // Always better to provide a generic error. You don't want malicious users to know which part they're getting wrong.
}
}
Im trying to first, check if both fields are not empty. if empty, alert user its empty. Then check if both user and password math and if they do match, then alert('welcome'). but if I type anything in the boxes, it passes and says welcome? Help!
const container = document.querySelector('.container');
const userInput = document.querySelector('#username');
const passInput = document.querySelector('#password');
const button = document.querySelector('button');
button.addEventListener('click', () => {
if (!userInput.value || !passInput.value) {
alert('One or more fields are empty. Please enter password and username');
}
if (!userInput.value == 'user21' || !passInput.value == 'user21') {
alert('password or username inavlid')
} else if (userInput.value == 'user21' && passInput.value == 'user21') {
alert(`Welcome ${userInput.value}`);
}
})*
Remove * at the end of your code and put ;
This:
if (!userInput.value == 'user21' || !passInput.value == 'user21') {
evaluates the ! first. It's like:
if ((!userInput.value) == 'user21' || (!passInput.value) == 'user21') {
which of course won't result in the comparison you want.
Check if the username and password match, and if they don't, just have a plain else, without an else if there.
button.addEventListener('click', () => {
if (!userInput.value || !passInput.value) {
alert('One or more fields are empty. Please enter password and username');
} else if (userInput.value == 'user21' && passInput.value == 'user21') {
alert(`Welcome ${userInput.value}`);
} else {
alert('password or username inavlid')
}
})
Also consider
using a proper modal instead of alert
if this is something you want any sort of reasonable security for, validate the logins using a backend database instead of hard-coding it on the front-end (which is trivially bypassable)
The following code loops when the page loads and I can't figure out why it is doing so. Is the issue with the onfocus?
alert("JS is working");
function validateFirstName() {
alert("validateFirstName was called");
var x = document.forms["info"]["fname"].value;
if (x == "") {
alert("First name must be filled out");
//return false;
}
}
function validateLastName()
{
alert("validateLastName was called");
var y = document.forms["info"]["lname"].value;
if (y == "") {
alert("Last name must be filled out");
//return false;
}
}
var fn = document.getElementById("fn");
var ln = document.getElementById("ln");
fn.onfocus = validateFirstName();
alert("in between");
ln.onfocus = validateLastName();
There were several issues with the approach you were taking to accomplish this, but the "looping" behavior you were experiencing is because you are using a combination of alert and onFocus. When you are focused on an input field and an alert is triggered, when you dismiss the alert, the browser will (by default) re-focus the element that previously had focus. So in your case, you would focus, get an alert, it would re-focus automatically, so it would re-trigger the alert, etc. Over and over.
A better way to do this is using the input event. That way, the user will not get prompted with an error message before they even have a chance to fill out the field. They will only be prompted if they clear out a value in a field, or if you call the validateRequiredField function sometime later in the code (on the form submission, for example).
I also changed around your validation function so you don't have to create a validation function for every single input on your form that does the exact same thing except spit out a slightly different message. You should also abstract the functionality that defines what to do on each error outside of the validation function - this is for testability and reusability purposes.
Let me know if you have any questions.
function validateRequiredField(fieldLabel, value) {
var errors = "";
if (value === "") {
//alert(fieldLabel + " must be filled out");
errors += fieldLabel + " must be filled out\n";
}
return errors;
}
var fn = document.getElementById("fn");
var ln = document.getElementById("ln");
fn.addEventListener("input", function (event) {
var val = event.target.value;
var errors = validateRequiredField("First Name", val);
if (errors !== "") {
alert(errors);
}
else {
// proceed
}
});
ln.addEventListener("input", function (event) {
var val = event.target.value;
var errors = validateRequiredField("Last Name", val);
if (errors !== "") {
alert(errors);
}
else {
// proceed
}
});
<form name="myForm">
<label>First Name: <input id="fn" /></label><br/><br/>
<label>Last Name: <input id="ln"/></label>
</form>
Not tested but you can try this
fn.addEventListener('focus', validateFirstName);
ln.addEventListener('focus', validateLastName);
I'm having problems getting this code to validate when clicking on the login button.
** my html code **
<form action="abc.php"
method="post"
onsubmit="return jcheck();">
<div id="id_box">
<input type="text"
name="email"
id="id_text" placeholder="E-mail" >
<div id="pass_box">
<input type="password"
name="password" id="pass_text" placeholder="Password">
<div id="submit_box">
<input
type="submit"
id="sub_box"
onClick="click_event()"
value="Login">
my javascript code:
function click_event(){
jcheck();
function validate_ID(){
var email = document.getElementById('id_text');
var filter = /^[a-z0-9](\.?[a-z0-9]){1,}#threadsol\.com$/;
var filter1 = /^[a-z0-9](\.?[a-z0-9]){1,}#intellocut\.com$/;
var flag=0;
if (filter.test(email.value)==false
&& filter1.test(email.value)==false ) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#e_asterics").html("");
return false;
} else
return true;
}
function validate_Pass() {
var pass =document.getElementById('pass_text');
var filter = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s). 4,}$/;
if (filter.test(pass.value)==false ) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#p_asterics").html("");
return false;
} else
return true;
}
function jcheck();
$("#e_asterics").html("");$("#p_asterics").html("");
$('#warn_text').html("");$('#warn_pass').html("");
var name = jQuery.trim($("#id_text").val());var pas = jQuery.trim($("#pass_text").val());
if ((name.length == 0) && (pas.length == 0)) {
$('#warn_text').html("*Indicates required field");
$('#warn_pass').html("* Indicates required field");
$("#e_asterics").html("*");$("#p_asterics").html("*"); }
else if (name.length == 0)) {
$("#e_asterics").html("*");
$("#p_asterics").html("");
$('#warn_pass').html("Email Id Required");
} else if ((pas.length == 0)) {
if(name.length != 0)
{
validate_ID();
} else {
$("#e_asterics").html("*");
$('#warn_text').html("Enter Email Id");
}
$("#p_asterics").html("*");
$('#warn_pass').html("Password Required");
}
}
return false;
}
For starters you should always indent your code so errors are easier to find. I helped you do a bit of indenting and there are a lot of problems in the code. One thing you are doing wrong is you need to close functions, else branches and html tags.
All HTML tags should end with an end tag or be closed immediately.
Example <div></div> or <div /> if you don't do this the browser may render your page differently on different browsers. You have missed this on your input tags you divs and your form tag. Perhaps you should check the whole html document for more of these errors.
Functions should in javascript should always look like this
function name(parameters, ...) {
}
or like this
var name = function(parameters, ...) {
}
the the name and parameters may vary but generally the function should look like this.
if statements else branches and else if branches should all have enclosing brackets for their code.
if () {
//code
} else if () {
//code
} else {
//code
}
If you do not close start and close else brackets the javascript will behave in very strange and unexpected ways. In fact i think your code might not even compile.
If you are using chrome please press Ctrl + Shift + J and look in the Console tab. You should see some error messages there. When you click the submit button.
Also using onClick on the submit button may be dangerous as I don't think this blocks submit. A better way to achieve the requested functionality is probably to either use a button type input and go with onClick or use the onSubmit function on the form. You are currently using both and its really no way to tell if click_event or jcheck will run first. Perhaps you should debug and see in which order the function calls happen. You can use chrome to debug by pressing CTRL + Shift + J and setting debug points in the Source tab.
You have a minor stylistic error as well where you compare the result of the regexp test() with false. The return value of test is already a Boolean and does not need to be compared.
Here is a guestimation of how the HTML should look. Its hard to say if its right as I have no more info to go on than your code and it has a lot of problems.
<form action="abc.php" method="post" onsubmit="return jcheck();">
<div id="id_box">
<input type="text" name="email" id="id_text" placeholder="E-mail" />
</div>
<div id="pass_box">
<input type="password" name="password" id="pass_text" placeholder="Password">
</div>
<div id="submit_box">
<input
type="submit"
id="sub_box"
value="Login" />
</div>
</form>
Here is what the js might look like. Here the missing brackets makes it difficult to tell where functions should end so I have had to guess a lot.
/* I find it hard to belive you wanted to encapsule your functions inside the
click_event function so I took the liberty of placing all
functions in the glonbal scope as this is probably what you inteneded.
I removed the click_event handler as it only does the same thing as the onSubmit.
*/
function validate_ID() {
var email = document.getElementById('id_text');
var filter = /^[a-z0-9](\.?[a-z0-9]){1,}#threadsol\.com$/;
var filter1 = /^[a-z0-9](\.?[a-z0-9]){1,}#intellocut\.com$/;
var flag=0;
// Or feels better here as there is no way the email ends with bot #intellocut and #threadsol
// It also feels strange that these are the invalid adresses maby you messed up here and should change
// the contents of the else and the if branch.
if (filter.test(email.value) || filter1.test(email.value)) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#e_asterics").html("");
return false;
} else {
return true;
}
}
// This funcion is not used Im guessing you should have used it in
function validate_Pass() {
var pass =document.getElementById('pass_text');
/* The filter below could cause problems for users in deciding password unless
you tell them some where what the rules are.
It was missing a { bracket before the 4 at the end that I added make sure
it is right now. If you are going to use the code.
*/
var filter = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s). {4,}$/;
if (filter.test(pass.value)) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#p_asterics").html("");
return false;
} else {
return true;
}
}
/* There are betterways to deal with multiple validation than chaining them like
this but Im guessing this will work. Im guessing that if you want to use the
password validation you should call it some where in this function.
like so 'validate_Pass()'
*/
function jcheck() {
$("#e_asterics").html("");$("#p_asterics").html("");
$('#warn_text').html("");$('#warn_pass').html("");
var name = jQuery.trim($("#id_text").val());var pas = jQuery.trim($("#pass_text").val());
if ((name.length === 0) && (pas.length === 0)) {
$('#warn_text').html("*Indicates required field");
$('#warn_pass').html("* Indicates required field");
$("#e_asterics").html("*");
$("#p_asterics").html("*"); }
else if (name.length === 0) {
$("#e_asterics").html("*");
$("#p_asterics").html("");
$('#warn_pass').html("Email Id Required");
} else if (pas.length === 0) {
if(name.length !== 0) {
validate_ID();
} else {
$("#e_asterics").html("*");
$('#warn_text').html("Enter Email Id");
}
}
}
function send() {
alert("Your message sent.");
}
function wrongNickNameorMessage() {
var nicknameValue = document.getElementById("input-nickname").value;
var messageValue = document.getElementById("input-text").value;
if (nicknameValue != "" && messageValue != "") {
document.getElementById("af-form").submit();
} else {
alert("Nickname or message is blank. Please fill.");
return false;
}
}
These are my JS codes
<input type="text" name="nickname" id="input-nickname" required>
<textarea name="message" type="text" id="input-text" required></textarea>
<input type="submit" value="Send" onclick="wrongNickNameorMessage() + send()" />
And these are my HTML codes.
When I click on Send button. First alert("Your message sent."); then alert("nickname or message is blank. Please fill."); is working. Or exact opposite.
I wanna disabled send() function if wrongNickNameorMessage() is true.
How can I do that?
You have the right idea but you're going about it very out-of-the-way. Try this:
function wrongNickNameorMessage() {
var nicknameValue = document.getElementById("input-nickname").value;
var messageValue = document.getElementById("input-text").value;
if (nicknameValue === "" || messageValue === "") {
alert("Nickname or message is blank or improper input detected. Please fill.");
return false;
}
document.getElementById("af-form").submit();
alert("Your message sent.");
}
You dont need the other function or the other part of the if statement since you're just validating input. You can get more creative but that's all you really need. Your function will completely stop if there's a problem but otherwise, it'll show the right message and submit.
Although your practice is horrible, this may help you in the future:
/* first give your submit button an id or something and don't use the onclick
attribute
*/
<input type='submit' value='Send' id='sub' />
// Now the JavaScript, which should be external for caching.
var doc = document;
// never have to use document.getElementById() again
function E(e){
return doc.getElementById(e);
}
function send() {
alert('Your message was sent.');
}
// put all your sub onclick stuff in here
E('sub').onclick = function(){
var nicknameValue = E('input-nickname').value;
var messageValue = E('input-text').value;
if(nicknameValue !== '' && messageValue !== '') {
send(); E('af-form').submit();
}
else {
alert('Nickname or message is blank. Please fill.');
return false;
}
}
Note, that this is not sufficient to handle a form. It just shows concept. JavaScript can be disabled, so you must account for that as well, Server Side.
You need to call a wrapper method that will call the wrongNickNameorMessage() check result and than continue only if returned true.
function conditionalSend(){if (wrongNickNameorMessage()){send();}}