var password=123;
var input;
var opp=0;
for(var t=0;t<=2;t++){
if(password!=input && t<=2){
input=prompt("enter your password");
}
else{
opp++;
}
}
if(opp!=0){
alert("success");
}
else if(opp<1){
alert("fail");
}
im expect it to be a password validation which can only try three times.
but it will failed even with typing correct password in the third try.
Let's begin saying this should just be a didactic excercise.
I suggest you to drop the for loop strategy and embed the logic inside a while loop that will keep running as long as the attempt counter variable will be <=3.
Until the typed password still doesn't match the expected one, it will keep asking for a new password after saying fail for a total amount of 3 attemps max.
If the typed password matched, it just alerts the user saying success and exiting the loop.
Of course as just said by other users, this approach is very wrong in terms of security starting from the fact that the expected password is stored in plain text.
As a side note, the expected password defined as a literal should be a string literal and not a number.
let password = '123';
let attempt = 0;
let input;
let wasSuccess = false;
while(++attempt<=3){
input = prompt("enter your password");
if(input == password){
wasSuccess = true;
alert('success');
break;
}else{
alert('fail');
}
}
if(wasSuccess){
//perform any logic expected to run after successfully logged in
}
I am not sure what it is you are trying to do, this is totally unsafe.
To easily crack your password challenge, click 'view source' on the browser, and lookup the password.
Please use better authentication, preferably on the server, not in javascript.
Of course you can use Javascript, but not for actual password checking.
Since OP is just trying and will never use this in a production environment, here is a working piece of script:
var password= "123";
var input;
var tries=1;
var maxTries = 5;
var passed = false;
while ( (!passed) && (tries <= maxTries) ){
input=prompt("enter your password (attempt nr "+tries+")");
if (input === password){
passed = true; // Yeah!
} else {
tries = tries + 1;
}
}
if (passed){
alert("success");
} else {
alert("fail");
}
Related
When you input wrong password, incorrect alert show, but second time when you do it, it just let you on site.
var password = "Password123";
var pass = window.prompt("Enter password: ");
if (pass == sifra) {
alert("Correct");
} else {
var pass = window.prompt("Incorrect password: ");
}
You cause your code has no checks after the second prompt. In this scenario, You should write your code in a kind of recursion way. When the password check fails, It should begin the same process again and again until it passes.
// fn: verify the password
function verifyPassword(pass) {
if (pass === "sifra") {
alert("Correct");
} else {
// prompt the password again if it's incorrect
promptPassword("Incorrect password: ");
}
}
// fn: promoting the password
function promptPassword(msg = "Enter password:") {
var pass = window.prompt(`${msg} `);
// verify the password
verifyPassword(pass);
}
promptPassword();
This is happening because second time its just taking input but not validating password if you want to validate password untill its correct you can try this just add a loop
var pass = window.prompt("Enter password: ");
while (pass !== sifra) {
pass = window.prompt("incorrenct password try again: ");
}
// reaches here only when password is corrent
I have been creating JavaScript validation for a form though run into difficulties. There are currently two parts to parts at (at the moment) for JavaSCript to check (email and sms). THe script is only running email and not checking sms at all when should be checking both together. If both are fine then return true. Any ideas?
function validateForm() {
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
var errordiv = document.getElementById('error');
var errorsms = document.getElementById('errorsms');
/*postOptOutSix.checked = false;
postOptOutForever.checked = false*/
// Conditions
if (document.getElementById("emailradios") ==null && document.getElementById("emailforever") ==null) {
if (document.getElementById("smsforever") ==null && document.getElementById("smsforever") ==null) {
return true;
}
else if (document.getElementById("checksms").checked ==false && document.getElementById("smsOptOutSix").checked ==false && document.getElementById("smsOptOutForever").checked ==false) {
errordiv.innerHTML += "<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
else if (document.getElementById("checkemail").checked ==false && document.getElementById("emailOptOutSix").checked ==false && document.getElementById("emailOptOutForever").checked ==false) {
errorsms.innerHTML += "<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
You'd need to separate the 2 conditions checks, and only then check if some failed or not before returning.
Something like this should do the trick:
function validateForm () {
var errors = [];
// Empty any previous errors
document.getElementById('error').innerHTML = "";
// Check for SMS
if (!document.getElementById("checksms").checked &&
!document.getElementById("smsOptOutSix").checked &&
!document.getElementById("smsOptOutForever").checked) {
// add the SMS error to the array
errors.push("<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'");
}
// Check for Email
if (!document.getElementById("checkemail").checked &&
!document.getElementById("emailOptOutSix").checked &&
!document.getElementById("emailOptOutForever").checked) {
// add the Email error to the array
errors.push("<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'");
}
// Display the error(s) if any
if (errors.length > 0) {
errors.forEach(function (err) {
document.getElementById('error').innerHTML += err;
});
return false;
}
return true;
}
Also, I noticed that id='errorp' is there twice. Rename one of them.
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
You are setting the same variable from different elements. Shouldn't it be like this?
var emailBoxChecked = document.getElementById("checkemail").checked
var smsBoxChecked = document.getElementById("checksms").checked
Use HTML required and pattern attributes along with inputElement.checkValidity() which returns true or false. You could look on keyup, for example, to make sure all inputs are valid and if so enable the submit button and if not disable it.
I'm trying to figure out why validation is always fails? Regular expressions should be fine, I guess the problem should be somewhere in if(loginreg.test(login) && passwordreg.test(password) && repassword==password). Could someone please help me with it?
function CheckAuthData() {
var loginreg = /^(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{4,}\d$/g;
var login = document.getElementById("login").value;
var passwordreg =
/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{1,}$/g;
var password = document.getElementById("password").value;
var repassword = document.getElementById("repassword").value;
if(loginreg.test(login) && passwordreg.test(password) && repassword==password){
document.getElementById("labellogin").innerHTML = "";
document.getElementById("labelpassword").innerHTML = "";
document.getElementById("labelrepassword").innerHTML = "";
document.getElementById("pers_data").style.display = "block";
}
if(!loginreg.test(login)){
var label = document.getElementById("labellogin").innerHTML = "Login error!";
document.getElementById("labellogin").style.color = "red";
}
if(!passwordreg.test(password)){
document.getElementById("labelpassword").innerHTML = "Password error!";
document.getElementById("labelpassword").style.color = "red";
}
if(repassword!=password){
document.getElementById("labelrepassword").innerHTML =
"Should be the same password!";
document.getElementById("labelrepassword").style.color = "red";
}
}
The only actual error I can see there is that if any of those conditions fails once, you never clear the red off the element where it happened. But since you clear the text out of the element, it probably doesn't matter.
That said, testing the same conditions twice (in your first if and then again in subsequent ones, inverted) is a maintenance problem waiting to happen, as is all of the repeated code in the function.
You also don't need to recreate the regular expressions every time the function is called, and you don't need the g flag on them.
This addresses the various issues above (note: I'm assuming this is contained in some kind of scoping function, so we're not creating new globals by moving those regexes out):
var loginreg = /^(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{4,}\d$/;
var passwordreg =
/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{1,}$/;
function CheckAuthData() {
var login = document.getElementById("login").value;
var password = document.getElementById("password").value;
var repassword = document.getElementById("repassword").value;
var failed = false;
updateField("labellogin", loginreg.test(login), "Login error!");
updateField("labelpassword", passwordreg.test(password), "Password error!");
updateField("labelrepassword", repassword == password, "Should be the same password!");
if(!failed) {
document.getElementById("pers_data").style.display = "block";
}
function updateField(id, valid, message) {
var element = document.getElementById(id);
element.innerHTML = valid ? "" : message;
element.style.color = valid ? "" : "red";
failed = failed || !valid;
}
}
Made this a CW because...well...it probably doesn't actually answer the question, because there isn't enough info in the question. But hopefully it's helpful.
Hi folks I was curious if someone could help me out. I don't usually post on here but I have exhausted all my efforts and can't figure this out. I have this code here
function insertVideo(link)
{
if (link)
{
if(link.substring(0,29)!="http://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
else{
link = link.replace(/watch\?/,"").replace(/\=/,"/");
}
var editpane = document.frmPost.addesc;
var linkcode = "[EMBED]" + link + "[/EMBED]";
editpane.focus();
/*if (document.selection)
{
document.selection.createRange().text = linkcode;
}
else*/
if (editpane.selectionStart || editpane.selectionStart == '0')
{
var selstart = editpane.selectionStart;
var selend = editpane.selectionEnd;
editpane.value = editpane.value.substring(0, selstart) + linkcode + editpane.value.substring(selend);
editpane.selectionStart = selstart + linkcode.length;
editpane.selectionEnd = editpane.selectionStart;
}
else
{
editpane.value = editpane.value + linkcode;
}
editpane.focus();
}
}
The problem I am having is when the user trys top post a youtube video with https in the address.
I understand that if I change
{
if(link.substring(0,29)!="http://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
to
{
if(link.substring(0,30)!="https://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
It works. But then when the user enters the http address without the https it no longer works. I figured I could combine the statement with an OR, but this doesnt work either, I had
if(link.substring(0,29)!="http://www.youtube.com/watch?" || link.substring(0,30)!="https://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
else{
link = link.replace(/watch\?/,"").replace(/\=/,"/");
}
So basically I need it to work in both situations (https and http) not just one or the other.
I am stumped, Im no pro with javascript so I sure its a minor error but I have spent far too much time trying to figure this out on my own. Please help if you can. Thanks!
It's as simple as changing the OR (||) to an boolean AND (&&).
if (link.substring(0,29) !== "http://www.youtube.com/watch?" && link.substring(0,30) !== "https://www.youtube.com/watch?") {
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
// the else is unnecessary
// else {
link = link.replace(/watch\?/,"").replace(/\=/,"/");
// }
This works as in your original code, if your URL is http://, it will fail the https:// check (or vice versa), making the conditional true, therefore running your failure code. Changing it to && fixes it as the URL is now required to fail both tests to be invalid.
Just a little note: unless you're doing it deliberately (or in other special circumstances), you should use the === and !== forms of equality testing (instead of == and !=), as these fail automatically if they are of different types instead of converting the types implicitly.
I've got no clue how to do the following, so I wasn't sure what to search for either.
For validating my registration form I've a javascript function that checkes the existence of the inserted username in the database onblur of the username textfield.
function checkUsername(username){
$.post("checkmail.php", {username: username} , function(data){
var $response=$(data);
var response = $response.filter('#username-response').text();
if(response == "taken") {
document.getElementById('username').style.borderColor = rood;
valid = false;
}
});
}
This works fine, but now I want to validate it again onsubmit of the form in case users decide to submit an existing username.
function validateForm() {
var valid = true;
//checks different fields
//now check voor username existence
var username = document.getElementById('username').value;
checkUsername.call(username);
if (!valid) {
return false;
}
else {
return true;
}
}
I'm not familiar enough with Javascript to get this working. Probably thinking in the wrong direction...
You can use synchronous ajax call for this as you are using return data for validation.