function studentName(x) {
while (x == '' || x >= 0 || x < 0) {
if (x == '') {
x = prompt('Cannot leave field blank. Enter again');
} else if (x >= 0) {
x = prompt('Cannot Enter a number. Enter again')
} else {
x = prompt('Cannot Enter a number. Enter again')
}
}
return (x)
}
function studentScore(y) {
while (y == '' || y > 100 || y < 0 || isNaN(y)) {
if (y == '') {
y = parseFloat(prompt("Cannot leave field, blank please enter students score"));
} else if (y > 100 || y < 0) {
y = parseFloat(prompt("Invalid score, please enter a score 0-100"));
} else {
y = parseFloat(prompt("Invalid score, please enter a score 0-100"));
}
}
return (y)
}
function another(z) {
while (z == '' || z != 'n' && z != 'N' && z != 'y' && z != 'Y') {
if (z != 'n') {
z = prompt('Invalid Option. Enter another score Y or N')
} else if (z != 'N') {
z = prompt('Invalid Option. Enter another score Y or N')
} else if (z != 'y') {
z = prompt('Invalid Option. Enter another score Y or N')
} else if (z != 'Y') {
z = prompt('Invalid Option. Enter another score Y or N')
} else if (z == '') {
z = prompt('Invalid Option. Enter another score Y or N')
}
}
return (z)
}
var names = []
var scores = []
var redo = true
var anotherName
var redo2
var retry = true
var anotherScore
var retry2
var i = 0
var a = 1
var score = 0
while (redo == true) {
var studentNames = prompt('Enter student name');
var name = studentName(studentNames);
names.push(name)
while (retry == true) {
var studentScores = parseFloat(prompt('Enter student score'));
score = score + studentScore(studentScores);
retry = prompt('Enter another score? Y/N');
retry2 = another(retry);
if (retry == 'y' || retry == 'Y') {
retry = true
a++
} else if (retry == 'n' || retry == 'N') {
retry = false
}
}
score = score / a
scores[i] = score
redo = prompt('Enter another student? Y/N');
redo2 = another(redo);
if (redo == 'y' || redo == 'Y') {
redo = true
retry = true
i++;
a = 1
score = 0
} else if (redo == 'n' || redo == 'N') {
redo = false
}
}
var message = ""
for (y = 0; y < names.length; y++) {
alert(names[y] + " - " + scores[y]);
}
when asked if the person wants to enter another score and Y or N and i enter something x i do get a prompt that says enter another score but once i say yes instead of asking for the score it goes straight into asking if i would like to enter another student instead of asking for the score also when you enter something that should be invalid you get stuck with the same problem but a bit diffrent first off it says invalid enter another score not another student and when you enter Y for yes it stops the program a
thanks for the help!
it would probably be best to run the program a bit to fully grasp the issue it is difficult to explain the problem.
Your main problem is these 3 lines
retry = prompt('Enter another score? Y/N');
retry2 = another(retry);
if(retry == 'y' || retry == 'Y')
{
...
You are only using the first input (retry) in your if statement (which can be bad input). If it is bad input retry2 will hold the valid input (but you don't use that in your if condition).
You are ignoring the second attempt and using the first invalid input which exits your student score while loop because retry is bad input and not true anymore.
You can fix this by just changing retry2 = another(retry); to retry = another(retry);
I would also suggest using separate variables for the while statement and your prompt variable.
it also looks like you will have the same problem with redo and redo2
let age = "";
while (age !== NaN) {
age = prompt("what is your age");
Number(age);
}
I can not leave the while loop although I write a number in the prompt box, why?
You can use isNaN() function to determine whether a value is NaN or not. You have to add age == "" as part of the condition with || to pass for the initial value (empty string).
The condition should be:
while (isNaN(age) || age == "")
You also have to re-assign the converted value to the variable.
let age = "";
while (isNaN(age) || age === "") {
age = prompt("what is your age");
if(age == null)
break;
else
age = Number(age);
}
I am making a simple user registration page with only 3 fields, Email, password and repeat-password.
I have some conditions for the password to be accepted for example it should not contain the following letters: "e" "k" "n" "m", it should be between 6 and 11 letters and also there are more validation like the first letter needs to be a Capitol letter, and the rest lower case letters.
I have so far made a simple react application with email and password, some of the validations works for example the length but I am not sure how to add the other validations and if I know I think I need to use ASCII to convert letters to number so I can make the comparison.
validateField(fieldName, value) {
let fieldValidationErrors = this.state.formErrors;
let emailValid = this.state.emailValid;
let passwordValid = this.state.passwordValid;
switch(fieldName) {
case 'email':
emailValid = value.match(/^([\w.%+-]+)#([\w-]+\.)+([\w]{2,})$/i);
fieldValidationErrors.email = emailValid ? '' : ' is invalid';
break;
case 'password':
passwordValid = value.length >= 6 && value.length <= 11;
fieldValidationErrors.password = passwordValid ? '': ' is not valid';
//fieldValidationErrors.password = passwordValid.includes('e') ? '': 'contains i';
break;
default:
break;
}
this.setState({formErrors: fieldValidationErrors,
emailValid: emailValid,
passwordValid: passwordValid
}, this.validateForm);
}
function check(value){
return (value.length >= 6 && value.length <= 11) && (value.match(/[e,k,n,m]/) === null) || /^[A-Z][a-z]+$/.test(value)
}
console.log(check("asdfg"))
console.log(check("Asdfg"))
console.log(check("aDdfg"))
console.log(check("Asdfgee"))
this contains all your three checks,
var passwordValid = (value.length >= 6 && value.length <= 11) && (value.match(/[e,k,n,m]/) === null) || /^[A-Z][a-z]+$/.test(value)
How would you make an if/else statement loop back to the beginning to get user information?
This is the code I got so far:
var age = prompt("Please enter your age");
if(age == 21 ) {
alert("Happy 21st Birthday!");
} else if (age > 21 ) {
alert("You are old");
} else {
alert("Please enter an age");
}
I'm trying to make it go back to the beginning to make the user enter information.
var age = '';
while(age == '' || age == 'ok'){
age = prompt("Please enter your age");
if($.isNumeric(age) === false){
continue;
}
if(age == 21 ){
alert("Happy 21st Birthday!");
continue;
}
if (age > 21 ){
alert("You are old");
continue;
}
if (age < 21){
alert("You are too young to be in this bar!");
}
}
for (let age = prompt('Please enter your age'); ;) {
if (age == 21) {
alert('Happy 21st Birthday!');
break;
} else if (age > 21) {
alert('You are old');
break;
} else {
age = prompt('Please enter your age');
}
}
You separate validation logic from the user input logic.
If this is console app then you would place a loop around the prompt and then validate the user age, if the age is valid break out of the loop otherwise let the loop continue.
On a web page you would wrap it in a function and based on the result manipulate the view based on if the age is correct or not. So you would perhaps show an error message if the age is invalid or go to the next page if the age is valid.
You should wrap the if statements which make up the validation logic in into a function perhaps validateAge that returns true or false, that way no matter what you implement you can use the same method.
Working off of #wallyk's suggestion using a while loop yields this example:
var age = false;
while (!age) {
age = prompt("Please enter your age");
if (age == 21) {
alert("Happy 21st Birthday!");
} else if (age > 21) {
alert("You are old");
} else if (!!age && age < 21) {
alert("You are young");
} else {
alert("Please enter an age");
age = false;
}
}
It will keep looping until you type a valid number answer. I also added in a check to see if the user input an age under 21, since I'm guessing you don't want to keep looping forever if the user is under 21 (or keep looping until they turn 21) but that part can easily be removed if you want.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am new with Javascript and ,I'm trying to write a password strength function.
But each time I enter a password, it returns only one value ("very strong").
I completely confused !!
Here is my Code :
function pwd_Validation()
{
var strength = new Array();
strength[0] = "Blank";
strength[1] = "Very Weak";
strength[2] = "Weak";
strength[3] = "Medium";
strength[4] = "Strong";
strength[5] = "Very Strong";
var password = document.getElementById('pwd')
if (password.length < 1)
var score = 1;
else if (password.length < 4)
score = 2
else if (password.length >= 8 && password.value.match(/[a-z]/))
score = 3;
else if (password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/))
score = 4;
else (password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/) && password.value.match(/.[!,#,#,$,%,^,&,*,?,_,~,-,£,(,)]/))
score = 5;
document.getElementById('spnPwd').innerHTML = strength[score];
if ( password.value = "")
document.getElementById('spnPwd').innerHTML = strength[0];
document.getElementById('spnPwd').style.color="#FF0000"
if ( strength[score] == 1)
document.getElementById('spnPwd').innerHTML = strength[1];
document.getElementById('spnPwd').style.color="#FF0000"
if ( strength[score] == 3)
document.getElementById('spnPwd').innerHTML = strength[3];
document.getElementById('spnPwd').style.color="#FFCC00"
if ( strength[score] == 4)
document.getElementById('spnPwd').innerHTML = strength[4];
document.getElementById('spnPwd').style.color="#19D119"
if ( strength[score] == 5)
document.getElementById('spnPwd').innerHTML = strength[5];
document.getElementById('spnPwd').style.color="#006600"
}
HTML code :
Password : <input type="password" id="pwd" onblur="pwd_Validation()" />
<span id="spnPwd" class="pwd_Strength" ></span><br />
There were several coding errors and logic errors. I would suggest this rewrite that makes the following fixes/improvements:
Get the actual password value and use its length instead of using the length of the password DOM element.
Handle the case of the length between 4 and 7 (a case your logic skipped)
Sequence the regex tests in the right order so it actually finds the proper score
Corrected the punctuation regex
Fix else logic problem
Put the colors into a parallel array.
Declare the strength strings in a more efficient/compact way.
Give your score a default value so it is guaranteed to have a value.
Don't repeat regex tests more than once
Use regex.test because it's more efficient than regex.match when all you want to know is if it matched
Pull the desired color value from the array rather than an if statement for every score
Only fetch the spnPwd DOM element once
Changed the numeric regex to \d
Use braces on all if/else statements for safety
And the suggested code:
function pwd_Validation() {
var strengths = ["Blank", "Very Weak", "Weak", "Medium", "Strong", "Very Strong"];
var colors = ["#FF0000", "#FF0000", "#FFCC00", "#FFCC00", "#19D119", "#006600"];
var score = 0;
var regLower = /[a-z]/, regUpper = /[A-Z]/, regNumber = /\d/, regPunctuation = /[.,!##$%^&*?_~\-£()]/;
var password = document.getElementById('pwd').value;
if (!password) {
score = 0;
} else if (password.length < 2) {
score = 1;
} else if (password.length < 4) {
score = 2;
} else if (password.length <= 7) {
score = 3;
} else {
// length is >= 8 in here
if (regLower.test(password) && regUpper.test(password) && regNumber.test(password)) {
// if it also has punctuation, then it gets a 5, otherwise just a 4
if (regPunctuation.test(password)) {
score = 5;
} else {
score = 4;
}
} else {
// if doesn't have upper, lower and numbers, then it gets a 3
score = 3;
}
}
var spanPwd = document.getElementById('spnPwd');
spanPwd.innerHTML = strengths[score];
spanPwd.style.color = colors[score];
}
There's an if missing from the last else so it's parsed like this:
...
else {
(password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/) && password.value.match(/.[!,#,#,$,%,^,&,*,?,_,~,-,£,(,)]/))
}
score = 5;
It's a good habit to always use brackets in control structures.
You forgot to convert the password field to its value:
var password = document.getElementById('pwd')
should be
var password = document.getElementById('pwd').value
In your original case, password.length is undefined, and all comparisons with it evaluate to false. (So the final else is executed)
Also, your last else block
else (password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/) && password.value.match(/.[!,#,#,$,%,^,&,*,?,_,~,-,£,(,)]/))
score = 5;
should be
else if(password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/) && password.value.match(/.[!,#,#,$,%,^,&,*,?,_,~,-,£,(,)]/))
score = 5;
Aside from that, please use braces in your ifs. It is bad practice to have code like this:
if(...)
...
else if(...)
...
else
...
This is better:
if(...){
...
}else if(...){
...
}else{
...
}
you save to the var score and then you ask strength[score]. if (strength[score] == 3)
then you are missing some { } in the second part of the code!
in the last part you can use
switch(score) {
case 1: ... break;
...
default: ... break;
}
I've pushed your code through jsbeautifier.org. This has reindented your code according to how a javascript interpreter would actually run it. Please notice how your if statements are not running the code you think they are.
function pwd_Validation() {
var strength = new Array();
strength[0] = "Blank";
strength[1] = "Very Weak";
strength[2] = "Weak";
strength[3] = "Medium";
strength[4] = "Strong";
strength[5] = "Very Strong";
var password = document.getElementById('pwd')
if (password.length < 1) var score = 1;
else if (password.length < 4) score = 2
else if (password.length >= 8 && password.value.match(/[a-z]/)) score = 3;
else if (password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/)) score = 4;
else(password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/) && password.value.match(/.[!,#,#,$,%,^,&,*,?,_,~,-,£,(,)]/))
score = 5;
document.getElementById('spnPwd').innerHTML = strength[score];
if (password.value = "") document.getElementById('spnPwd').innerHTML = strength[0];
document.getElementById('spnPwd').style.color = "#FF0000"
if (strength[score] == 1) document.getElementById('spnPwd').innerHTML = strength[1];
document.getElementById('spnPwd').style.color = "#FF0000"
if (strength[score] == 3) document.getElementById('spnPwd').innerHTML = strength[3];
document.getElementById('spnPwd').style.color = "#FFCC00"
if (strength[score] == 4) document.getElementById('spnPwd').innerHTML = strength[4];
document.getElementById('spnPwd').style.color = "#19D119"
if (strength[score] == 5) document.getElementById('spnPwd').innerHTML = strength[5];
document.getElementById('spnPwd').style.color = "#006600"
}
To take some particular examples out:
if (strength[score] == 5) document.getElementById('spnPwd').innerHTML = strength[5];
document.getElementById('spnPwd').style.color = "#006600"
Likely you intended this to be:
if (strength[score] == 5) {
document.getElementById('spnPwd').innerHTML = strength[5];
document.getElementById('spnPwd').style.color = "#006600"
}
Also:
else(password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/) && password.value.match(/.[!,#,#,$,%,^,&,*,?,_,~,-,£,(,)]/))
score = 5;
You probably meant:
else if (password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/) && password.value.match(/.[!,#,#,$,%,^,&,*,?,_,~,-,£,(,)]/)) {
score = 5;
}
The actual issue you mention in your code is because of the second conditional that I've pulled out. The line score = 5 is not part of any conditional, and will always be run (for reasons mentioned above). This is why you're always seeing that the passwords are "Very Strong".