If/Else statement nested in While loop - javascript

(I am very new to JavaScript and am writing this to try and get used to using it a bit more - which is why I'm using an object to store usernames and passwords. I'm learning this as part of an apprenticeship but this is during my own time to further my knowledge on JS)
I have tried writing a small piece of code that should ask the user to enter a username, which will be cross-checked against the property names in the object "userNames". The user is then asked to enter a password for this user which is then checked against the password set as the value of the corresponding property with the right username.
I feel as though part of the problem is to do with me trying to use the variable "enteredPassword" (set to the user's input for the password as a method) of "userNames".
If the username or password are incorrect after 3 attempts then I'd like the window to close.
my text editor is saying that the If statement is missing a branch and I'm not sure if this is affecting whether this works or not.
var userNames = {Tom:"PassW0rd", Bill:"Apples40C0lander", Ryan:"M1911p4ck4ge"};
var Greeting = "Insert Username:";
var i = 0;
while (i < 3)
{
var enteredUserName = prompt(Greeting);
var enteredPassword = prompt("enter password for " + enteredUserName);
if ((userNames.hasOwnProperty(enteredUserName)) && (userNames.enteredUserName==enteredPassword)) {
alert("Welcome");
break;
} else {
alert("incorrect Username or Password");
alert("");
window.open('', '_self', ''); window.close();
window.open('', '_self', ''); window.close();
i++
}}

A simple change is enough here :
userNames[enteredUserName].
In JavaScript, Object can also accessed like array.
If you use userNames.enteredUserName , then it will check {enteredUserName:somevalue} (ie, enteredUserName will be considered as a String. but if you use it as userNames[enteredUserName] , then enteredUserName will be considered as variable and index to the Object.
Try below snippet.
var userNames = {Tom:"PassW0rd", Bill:"Apples40C0lander", Ryan:"M1911p4ck4ge"};
var Greeting = "Insert Username:";
var i = 0;
while (i < 3)
{
var enteredUserName = prompt(Greeting);
var enteredPassword = prompt("enter password for " + enteredUserName);
if ((userNames.hasOwnProperty(enteredUserName)) && (userNames[enteredUserName]==enteredPassword)) {
alert("Welcome");
break;
} else {
alert("incorrect Username or Password");
alert("");
window.open('', '_self', ''); window.close();
window.open('', '_self', ''); window.close();
i++
}}

Related

JavaScript validation not working in installshield

Requirement : To validate password and emailID entered by user.
I have designed a dialog for user to enter there email id and password for creating their new account.
I want the the user input to be validated on the "next" button of the dialog.
I have written a JavaScript for it as shown below and added a custom action in "do action" of my dialog button.
function validatePassword(str szPasswordportal)
{
var newPassword = szPasswordportal;
var minNumberofChars = 6;
var maxNumberofChars = 20;
var regularExpression = /^[A-Za-z0-9`~!#%]{6,20}$/;
alert(newPassword);
if(newPassword = "") //if null
return false;
if(newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars)
{
return false;
}
if(!regularExpression.password(newPassword))
{
alert("password should contain atleast one number ,one alphabet and one special character");
return false;
}
return true;
}
But this JS is not getting executed successfully.
Can someone help me out with this or with some other suggestion?
Your if condition have a syntax mistake.
if(newPassword = "")
= is assigning operator. If you want to check the value you have to use conditional operator == like below.
if(newPassword == "")
Also you have to add all the condition on else part, then only it will check the validation one by one, otherwise at the end it will automatically return the true value. Change your script like below.
function validatePassword(str szPasswordportal)
{
var newPassword = szPasswordportal;
var minNumberofChars = 6;
var maxNumberofChars = 20;
var regularExpression = /^[A-Za-z0-9`~!#%]{6,20}$/;
alert(newPassword);
if(newPassword == "" || newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars)
{
return false;
} else if(!regularExpression.password(newPassword))
{
alert("password should contain atleast one number ,one alphabet and one special character");
return false;
} else {
return true;
}
}

How to validate email address match with website domain?

I have 2 input fields on my form: email and website
How do I use JQuery to validate the email address domain must matched with the website domain?
For example: if website is http://example.com or with www or without http:// or without http://www.
Then the email address field must be user#example.com
Here is my form https://jsfiddle.net/zm7e8r7p/
$(document).ready(function(){
$( "#target" ).submit(function( event ) {
var val = $("#website").val();
var myString = val.substr(val.indexOf("http://") + 7);
var emailString = $("#email").val();
var myEmail = emailString.substr(emailString.indexOf("#")+1);
if (myString == myEmail){
$( "span" ).text( "Validated..." ).show();
event.preventDefault();
}else{
$( "span" ).text( "Not valid!" ).show();
event.preventDefault();
}
});
});
You can use URL regex by Crockford
Getting only last two parts of domain name is optional, you can use it if you want to convert ww2.mobile.gmail.com into gmail.com. This logic will affect domain names like .co.in as #samanime points out
var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
var url = 'www.mobile.ora.co.in:80/goodparts?q#fragment';
var result = parse_url.exec(url);
var hostName = result[3];
console.log("host name: ", hostName);
lastTwo = hostName.split('.');
lastTwo = lastTwo.length>2?lastTwo.slice(Math.max(lastTwo.length - 2, 1)) : lastTwo;
onlyMainDomain = lastTwo.join('.');
console.log('only main domain:', onlyMainDomain);
var email = "someone#ora.co.in";
var emailDomain = email.split('#')[1];
console.log('email domain:', emailDomain);
console.log("valid?" , emailDomain === onlyMainDomain);
//check if email domain is a child of hostName
emailDomainRev = emailDomain.split('.').reverse();
hostNameRev = hostName.split('.').reverse();
var emailDomainIsChildOfHostName = true;
if(emailDomainRev.length > hostNameRev.length){
emailDomainIsChildOfHostName = false;
}
else{
emailDomainIsChildOfHostName = emailDomainRev.reduce(function(acc, item, index){
return acc && (item === hostNameRev[index]);
},true);
}
console.log("email domain is a child of host name:", emailDomainIsChildOfHostName);
Here is a simple JavaScript process to validate email with your domain name.
function ValidateEmail(email) {
var re = /\S+#\S+\.\S+/; /*Regular expression for valid email*/
return re.test(email); /*Return `true` if valid, Otherwise return `false`*/
}
var domain = 'www.example#example.com';
var email ='emaxple#example.com';
if(ValidateEmail(email)){
email = email.split('#'); /* Split email after `#` Sign*/
email = email[1] /*After split, `email[0]=emaxple, email[1]=emaxple.com`*/
domain = domain.split('').reverse().join(''); /*Now `domain = moc.elpmaxe#elpmaxe.www`*/
email = email.split('').reverse().join(''); /*Now `email = moc.elpmaxe*/
email = email + '#'; /*Now `email = moc.elpmaxe#`*/
if(domain.indexOf(email)==0){ /*If only return `0` then valid, Otherwise Invalid*/
/*Valid with your domain*/
}else{
/*Doesn't match with your domain*/
}
}else{
/*Invalid Email*/
}
I've added the regular expression Wiktor suggested with a minor change to accept url without protocol.
Your code would look like this:
$(document).ready(function(){
$("#target").submit(function(event) {
var website = $("#website").val();
var websiteDomain = website.replace(/^(https?:\/\/)?(?:www\.)?/, "");
var email = $("#email").val();
var emailDomain = email.substr(email.indexOf("#")+1);
$("span").text(websiteDomain === emailDomain ? "Valid!" : "Not valid!" ).show()
event.preventDefault();
});
});
There is a tricky part to your question. Technically, you can have a domain with any number of parts. For example: this.is.a.valid.domain.com
With the new custom top-level domains, it can get even trickier, since they make it possible to have all kinds of crazy combinations and lengths. For example: this.is.also.a.valid.name.on.the.top.level.cake
Looks nothing like a domain, but if you owned the top-level domain cake, you could make it happen.
So, you can't really trim off the sub-domain and ensure that www.example.com results in an email #example.com. However, you can tell if it's on at least #www.example.com, #example.com or #com, which could all be valid. (In reality, you couldn't have one on any of the controlled top-level domains, but it's probably good to allow it for those rare cases.)
This is why most websites require you to click a link in an email sent to you to validate your URL.
Using the above criteria I just described, you can do it with this:
var website = "http://www.example.com"; // website from form
var email = "me#example.com"; // email from form
var emailDomain = email.split('#')[1];
var websiteDomain = website.match(/^(?:https?:\/\/)?([^\/]+)/)[1];
var isValidEmail = (websiteDomain || '').lastIndexOf(emailDomain) === (websiteDomain || '').length - (emailDomain || '').length;
isValidEmail will then contain true if it is a valid match, or false if it isn't.
I've added checks for if something fails above so it won't throw an error if one of the above parts are bad. If you're giving an invalid website, websiteDomain will be undefined. Likewise for a completely invalid email, emailDomain will be `undefined.
I update your code. I give you the link here
https://jsfiddle.net/zm7e8r7p/5/
$(document).ready(function(){
$( "#target" ).submit(function(event) {
event.preventDefault();
var emailString = $("#email").val();
//cut rule by #
var afterAt = emailString.split('#');
var val = $("#website").val();
var myString = val.substr(-(afterAt[1].length));
console.log(afterAt[1].length);
if (myString == afterAt[1]){
console.log('works');return
}else{
console.log('not');return
};
});
});

JQuery keypress function not working

I have the following code which checks if a roll number is valid in the database selected by the postname variable. It was working in an earlier version where I hadn't introduced the second variable postname. But at the moment, this code is not working. What's the error here?
$(document).ready(function() { //function to check rollno is valid
$('#roll').keyup(function(event) {
var rolll=$('#roll').val();
var postname=$('#post').val();
$.get('CheckRollValidity',{roll:rolll},{post:postname},function(responseText) {
$('#status1').text(responseText);
});
});
});
Servlet
roll = request.getParameter("roll");
temp = request.getParameter("post");
table1 = "dbo."+post;
table2 = "dbo.user_candidates";
try
{
if (roll.length() < 10 || roll.length() > 10) {
result = "Please enter your " + len + "-digits roll number.";
count1 = 1;
}
else if (!roll.matches("[0-9]*"))
{
result = "Please enter digits only";
count1 = 1;
}
if (count1 == 0)
{
//database work
result="OK";
}
else
{
result = "Error";
}
}
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(result);
Also, can I do the same via ajax, alternatively? Here I don't want the code working on pressing a submit button. Rather the working is happening on keypress.
You can't send two objects, you'll have to use one object with two values otherwise the second object is seen as the argument which should have been the callback
$.get('CheckRollValidity',{roll:rolll, post:postname},function(responseText) {
$('#status1').text(responseText);
});

Javascript: registration form help required

I'm a rookie scripter and what I'm trying to do is: create a registration form and a calculator. If you enter a password less than 5 symbols or a username less than 3 symbols you will not be able to continue. But even if I enter an username with more than 3 symbols and a password with more than 5 symbols it still displays the error message.
The code: http://pastebin.com/KqYbDJMw
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
function triggerCalc(){
if (pw.length < 5 && user.length < 3){
alert("An error occured");
}
else {
alert("Thank you for registering to my website.");
var action = prompt("Welcome to my calculator. For addition press 1, for substraction press 2, for multiplication press 3, for division press 4 and for square root press 5:", "");
var firstNum = new Array();
var secondNum = new Array();
var result = new Array();
You want to fail if either of those conditions are true, so use || (or) instead of && (and)
if (pw.length < 5 && user.length < 3)
should be
if (pw.length < 5 || user.length < 3)
Also, you want to fetch the current values each time you do your check, so this
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
should be inside your function. Ie
function triggerCalc(){
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
The problem is you get :
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
function triggerCalc(){...
on load. So it will always be blank. To get it at the time the user clicks 'continue..' move it inside the function like so:
function triggerCalc(){
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
...
You are not too far off. The two main changes are you need to put your variable assignment inside of the function you are calling so it can get the values when the submit button is pressed.
Also you probably want to use an Or instead when validating the fields. Here is an example:
function triggerCalc(){
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
if (pw.length < 5 || user.length < 3){
alert("An error occured");
}
If you're doing any kind of validation, there are some great jQuery libraries that make it look great and are easy to implement. You might want to to a quick google search.

Code won't run due to string length issue

Got a simple Javascript program here to accept and check a password. It should:
Ask you to enter a new password
Check the strength of the password which outputs a message of either weak or strong based on a length of <6 or >6.
Get you to re enter this password to enter the 'system'
Give you simple prompts or 2 random letters if the password is not correct.
Everything works except the strong/weak checker. It has a problem getting the length of passwordEntry since it apparently doesn't exist as an entity.
Any ideas would be much appreciated
var pass;
var main = function(){
strengthCheck((prompt("Please Choose a New Password to Begin"));
}
var strengthCheck = new function(passwordEntry){
score = 0;
// adds to the score variable depending on the length of the password
if(passwordEntry.length > 6{
score=(score+1);
}
//reads messages back stating how strong password is based on length
if(score=0){
console.log("Your Password is Weak");
}
else if(score=1){
console.log("Your Password is Strong");
}
var passContinue = prompt("Do you want to continue with this password? Yes or no?")
if(passContinue === "no" || passContinue === "No"{
main();
}
else{
pass = passwordEntry;
console.log("Your new password has been changed to " + pass);
passwordChecker(prompt("Thank You. Please Enter Your Password Below"));
}
}
var passwordChecker = function (attempt){
if(attempt == pass){
console.log("Correct password. The system has logged you on");
}
else{
//if the password is wrong, runs the incorrectpassword() function
console.log("Incorrect Password");
IncorrectPass();
}
}
}
var IncorrectPass = function (){
var clueanswer = prompt("Do You Want A Clue");
if(clueanswer === "Yes" ||clueanswer === "yes"){
console.log("I will give you two random letters");
// takes two random locations from the string array and reads them back
var randarray1 = Math.floor((Math.random()*7)+1);
var randarray2 = Math.floor((Math.random()*7)+1);
var randletter1 = pass[randarray1];
var randletter2 = pass[randarray2];
console.log(randletter1+" "+randletter2);
passwordChecker("Please try entering your password again");
}
else{
console.log("GoodBye");
}
}
main()
This part looks very wrong:
if(score=0){
console.log("Your Password is Weak");
}
else if(score=1){
console.log("Your Password is Strong");
}
You should use == or === instead of = which is used for assignment rather than comparison.
This doesn't make sense either:
var main = function(){
strengthCheck((prompt("Please Choose a New Password to Begin"));
}
There are three opening parentheses and only two closing ones. Smells like parser error.
Change this...
var strengthCheck = new function(passwordEntry){
to this...
var strengthCheck = function(passwordEntry){
When you use new, you're not using it to create a new function. You're using it to call the function as a constructor, which will return an object. (An empty object in your case.)
Also, you have many syntax errors in your code. Use a code validator like http://jshint.com as well as a beautifier like http://jsbeautifier.org to clean up your code.

Categories