I'm fairly new to javascript and trying to list out the characters missing from a failed password to tell users what they need to input.
window.onload = function()
{
var info = document.getElementById("info");
var test = document.getElementById("myForm").test;
test.onclick = function(e)
{
e.preventDefault();
var pw = document.getElementById("myForm").pw.value;
var formula = /(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{6,}/;
if(formula.test(pw))
{
document.getElementById("myForm").submit();
}
else if pw.match(/\d/g) == null {
info.innerHTML = "You need a number";
console.log(pw.match(/\d/g))
} else {
info.innerHTML = "You need a number."
}
};
};
The above is just a first run through of checking if the user inputted a password with now numbers. But I keep getting an
Uncaught SyntaxError: Unexpected identifier
in chrome dev tools with the pw.match portion underlined. I've looked elsewhere online and my syntax looks correct. Where am I going wrong?
You need some parenthesis
else if (pw.match(/\d/g) == null) {
// ^ ^
You need parentheses around the condition of your if block.
else if (pw.match(/\d/g) == null) {
...
According to:
http://www.w3schools.com/js/js_if_else.asp
You have missed ( and ) in else if.
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 have this javascript and I get the error "function expected". I can't see anything wrong with my javascript. Please help. Thanks.
function checkrewardname()
{
var my=document.getElementById("Rname");
var con=my.value;
var mine=document.getElementById("forref").value.split('\n');
if (con == "")
{
alert("Enter a Reward Name.");
}
else
{
var i=0;
while(i<=mine.length)
{
if (mine(i) == con)//error here
{
alert("Duplicate reward. Please enter a new reward.");
}
else
{
document.getElementById("validate").click();
alert("The reward has been saved.");
}
i++;
}
}
}`
mine is an array but you are calling it as if it were a function. Use mine[i] rather than mine(i) and you'll access the array by index rather than generating an error. (Just a note; most C-style languages use [ and ] for array access and reserve ( and ) for function invocation).
You also have while(i<=mine.length)
shouldn't it be while(i < mine.length)
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.