I'm making a site with a login thing. The usernames/passwords will be stored in the website files as .txt. (I know it's not safe. This isn't meant to be safe. It's a test to see if people can crack one of the passwords). Here is the current code:
var attempt = 3;
function validate(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if ( username == "username" || username == "Username" && password == "B6YC98"){
window.location = "success.html";
return false;
}
else{
attempt --;
alert("You have "+attempt+" attempt(s) left;");
if( attempt == 0){
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
How would I make it so it checks if the username you entered, is equal to a username from usernames.txt? And the same for the passwords.
I might be confused, but all someone would have to do is watch the network traffic after doing your first login attempt to see that usernames.txt or password.txt are files being called. Then they could just access those directly?
But, assuming you don't mind that: Javascript - read local text file
Related
I've developed a simple login system in JS. When the password, the username or both are incorrect it's suposed to show an alert but now it shows 4. I know it is because of the for loop but I don't know how to get rid of it without breaking all the code. Thanks in advance =)
I leave here the piece of code:
function getName() {
var user = document.getElementById('Username').value;
var pass = document.getElementById('Password').value;
for (let f = 0; f < arr.length; f++) {
if (user == arr[f][0] && pass == arr[f][1]) {
document.write("Welcome back ", user, ", we've missed you");
}
if (user == arr[f][0] && pass != arr[f][0]) {
alert("Your password is incorrect");
}
else if (user != arr[f][0] && pass == arr[f][1]) {
alert("Your username is incorrect");
}
else {
alert("Unnexistant account");
}
}
}
Add break; after each document.write or alert statements.
Your instinct is correct, and a for loop is probably not ideal here. It is hard to read and debug and it's also kind of ugly. If you want to stick with it, the other answers show you how.
Assuming arr is an array of usernames & passwords, you can convert this into a Map and remove your loop completely.
const map = new Map();
arr.map(e => m.set(e[0], e[1]));
try {
if (map.get(user) === pass) {
document.write("welcome back " + user + ", we missed you.");
} else {
// although this might be too much info from a security standpoint.
document.write("incorrect password");
}
} catch (e) {
document.write("could not find user.");
}
If the username for one account is wrong, you don't want to tell them their account doesn't exist until you check it for every single account:
function getName() {
var user = document.getElementById('Username').value;
var pass = document.getElementById('Password').value;
for (let f = 0; f < arr.length; f++) {
if (user == arr[f][0] && pass == arr[f][1]) {
document.write("Welcome back ", user, ", we've missed you");
return; // exit from the function since we've found an account
}
if (user == arr[f][0] && pass != arr[f][0]) {
alert("Your password is incorrect");
return; // exit from the function since we've found a username match
}
}
// couldn't find match, alert
alert("Your account does not exist.");
}
I have a log in form and am trying to display an error message if the log is incorrect.
For example;
If (email and password match) then set validUser to true.
If validUser equals true then redirect to home page
Else redirect them back to log in and display one of 3 messages...
Messages are:
'Log in unsuccessful' if both email and password are incorrect
'Password incorrect' if just the password is wrong
'Email incorrect' if just the email is wrong
Is it possible to have a loop to do all this? I can't figure it out....
Trying something like this too:
if (validUser==false)
{
$("message").show();
}
else if ( ..........)
{
$("passwordmessage").show();
}
I also want to display a message on the page and so far using this:
document.getElementById('message').style.display = ""
Here is my code: http://jsfiddle.net/2pkn1qrv/
So, how could I use if statements to do this and how can I correctly display a html page element using javascript or jquery?
Please ask if you need any more code or require clarification.
P.s. these are my users details
var USERS = {
users: []
};
function User(type, email, password) {
this.type = type;
this.email = email;
this.password = password;
}
var A = new User("rep", "a#a.com", "a");
USERS.users.push(A);
var B = new User("rep", "b#b.com", "b");
USERS.users.push(B);
var C = new User("customer", "c#c.com", "c");
USERS.users.push(C);
var D = new User("grower", "d#d.com", "d");
USERS.users.push(D);
module.exports = USERS;
You wont be having 3 conditions in that case. you will check email availability and password match. If anyone fails, you can display the message. I couldnt test your code but this will be the logic and i assume Users.user[x].email is the list of emails from your database. If yes, sorry to say that its a bad practise.
validUser = false;
emailAvailable = false;
passwordIncorrect = false;
for (var x in USERS.users) {
if(!emailAvailable && emailLog === USERS.users[x].email){
emailAvailable = true;
} //Checks whether email is available.
if(emailAvailable && passwordLog === USERS.users[x].password){
passwordIncorrect = true;
break;
} //Checks whether the password is correct for that email.
} // end of for
if(!emailAvailable){
console.log("Email is incorrect");
}
else if(emailAvailable && !passwordIncorrect){
console.log("Password is incorrect");}
else{
validUser = true;
console.log("Valid User");
}
if(validUser){
//redirect
}
I think my way is it worth to give a try:
First: create a Javascriptobject:
function ruleToCheck(errorRule, errorMsgContainer)
{
this.errorCondition = errorRule;
this.errorMessage = errorMsgContainer;
}
after that create an array and fill it with your rules:
var rulesList = new Array();
rulesList.push(new ruleToCheck("validUser === true", "message"));
...
Then loop through the array:
var rulesListLength = rulesList.length;
var index = 0;
while (index < rulesListLength)
{
index++;
...
}
The secret of success is the powerful eval() function within the while() loop:
if (eval(rulesList[index].errorCondition))
{
$("#"+rulesList[index].errorMessage).show();
break;
//If 'break does not work, use 'index = rulesListLength'
}
Hope it was helpful or at least leaded you into the right direction.
By the way, take care of the comments on your question.
I'm trying to make a page out of javascript. I'm pretty new to all this, so bear with me.
I have a form, and when you press submit I have the following bit to see if the fields are left blank:
function calculatePrice()
{
var GasPrice = document.getElementById("number1").value;
var Distance = document.getElementById("number2").value;
var Mileage = document.getElementById("number3").value;
var norepeat = false;
if (norepeat==false && (GasPrice =="" || Distance =="" || Mileage ==""))
{
var para=document.createElement("p");
para.setAttribute("class", "error");
var node=document.createTextNode("All fields must be completed");
para.appendChild(node);
var element=document.getElementById("content");
element.appendChild(para);
var norepeat = true;
}
I created the error as a paragraph tag that appears. The problem is that when I press submit more than once, it writes the error message every time. I tried the norepeat variable thing, but it doesn't seem to be working. Any help?
Though I'm not completely sure your intentions, it'd have to look something more like:
var norepeat = false;
function calculatePrice() {
if(!norepeat && (/* other conditions here */)) {
norepeat = true;
}
return !(/* other conditions above */);
}
Where norepeat is defined in a global scope. Also, remember to use === as opposed to ==. And trimming the string before testing it wouldn't be a horrible idea...
But, wouldn't you want the errors to still persist if the user hasn't corrected them - isn't that the point of validation?
I think what you are trying to do is this. This assumes you add a new div "myError" that holds your error message. You'll also need to consider not submitting the form too if validation doesn't pass.
function calculatePrice() {
var GasPrice = document.getElementById("number1").value;
var Distance = document.getElementById("number2").value;
var Mileage = document.getElementById("number3").value;
var error = document.getElementById("myError");
if (GasPrice == "" || Distance == "" || Mileage == "") {
error.style.display = "block";
return false;
}
else {
error.style.display = "none";
return true;
}
}
I'm having trouble validating an HTML form with JavaScript. On their own they each work, but together they don't.
This works:
// Make sure the e-mail address is valid
function validateEmail(mailform,email) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.forms[mailform].elements[email].value;
if(reg.test(address) == false) {
alert('E-mail not valid');
return false;
}
}
Attribute in the form:
onsubmit="javascript:return validateEmail('mailform', 'email');"
And this works:
// Make sure the message is long enough
function validateBody(mailform,mailbody) {
var msg = document.forms[mailform].elements[mailbody].value.length;
if (msg < 3) {
alert('Too hort');
return false;
}
}
Attribute in the form:
onsubmit="javascript:return validateBody('mailform', 'mailbody');"
But this doesn't work:
// Make sure the e-mail address is valid AND that the message is long enough
function validateForm(mailform,email,mailbody) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.forms[mailform].elements[email].value;
var msg = document.forms[mailform].elements[mailbody].value.length;
if(reg.test(address) == false) {
alert('Please enter a valid e-mail address');
return false;
} else if (msg < 3) {
alert('Text too hort');
return false;
}
}
Attribute in the form:
onsubmit="javascript:return validateForm('mailform', 'email', 'mailbody');"
Why?
As I said, they work each on their own, but even as different functions, they don't work together.
If you have two functions which work, why not use those?
function validateForm(mailform,email,mailbody) {
var addressValid = validateEmail(mailform,email);
var bodyValid = validateBody(mailform,mailbody);
return addressValid && bodyValid
}
The return will only return true if both tests are true. The advantage of this method is (as well as being likely to work) that it's easily extended and easily maintained.
If you only want one alert if there are two errors, then you'll need to test addressValid and call bodyValid only if required.
Use if (msg < 3) instead of else if (msg < 3) .
You don't need to use javascript: in the onsubmit attribute, remove that part.
Also, you would benefit greatly from using a JavaScript library such as jQuery.
I take full advantage of GMail's wildcard feature (username+wildcard#gmail.com). Unfortunately it seems that most developers don't understand that + is valid in an email address. This makes trying to unsubscribe a real chore sometimes.
Take TicketMaster for example... immediately you notice that they didn't even bother escaping the email address, so the text field defaults to "user wilcard#gmail.com". Not a problem, we can just add the + manually. Once Submit is clicked, you'll notice the validation stops you right in your tracks. What now?
Most users would have to further contact TicketMaster and attempt to explain the situation. I opened up FireBug to investigate. That's when I noticed this whopping 74 line email validation function with so much redundancy it's ridiculous. My favorite check is on line 20, informing the user that his/her email cannot have more than one #. Unreal. My second favorite part is the TWO regular expressions used!
Imagine... someone was paid money for this... and by the looks of it, they were paid by the line count.
//Validates the email
function validateOptoutEmail(object) {
var emailStr = object.value;
if(emailStr == '' || emailStr == null) {
alert('Email can not be empty. Please provide email');
object.value = '';
object.focus();
return false;
} else if(Trim(emailStr).length == 0) {
alert('Email can not be empty. Please provide email');
object.value = '';
object.focus();
return false;
} else {
var atcount=0;
for(var i=0;i<emailStr.length;i++) {
if(emailStr.charAt(i)=='#') atcount++;
}
if(atcount>1) {
alert('Invalid email. Email cannot have more than one #');
object.value = '';
object.focus();
return false;
}
if(emailStr.indexOf('.') == -1) {
alert('Invalid email. Email must have one dot');
object.value = '';
object.focus();
return false;
}
if(emailStr.indexOf('..')!= -1) {
alert('Invalid email. Email cannot have consecutive dots');
object.value = '';
object.focus();
return false;
}
var dotpos=0;
for(var i=dotpos;i< emailStr.length;i++) {
var ichar=emailStr.charAt(i);
if(ichar=='.') dotpos=i;
}
for(var i=dotpos+1;i< emailStr.length;i++) {
var ichar=emailStr.charAt(i);
if((!isNaN(ichar)) || (ichar == '_')) {
alert('Invalid email. Email cannot have numbers or _ after dot');
object.value = '';
object.focus();
return false;
}
}
var pattern2=/^([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
var pattern1=/^[0-9a-zA-Z\-\_.]+#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if (pattern1.test(emailStr)) {
if(pattern2.test(emailStr)) {
return true;
} else {
alert('Invalid email');
object.value = '';
object.focus();
}
return true;
} else {
alert('Invalid email');
object.value = '';
object.focus();
return false;
}
alert('Invalid email');
object.value = '';
object.focus();
return false;
}
}
I eventually just put a break point in FireBug and changed the value of the email address passed into the validation function. From there everything worked fine...
All that said, how can we get the word out there that + is valid in an email address? Too often, I'm unable to use the email address that I want to use for certain web sites because developers simply aren't aware of what constitutes a valid email address.
Point them at the rfc:
https://www.rfc-editor.org/rfc/rfc5322#page-10
3.2.3 states "+" is a valid atom