Best way to validate long list of random postal codes - javascript

I have a long list of postal codes I have to validate.
Link to postal codes
As you can see it's quite random there is no real order.
I tried making a switch and put in everything by hand like so:
switch (true) {
case ($(this).val().length < 5) :
console.log("not filled out");
break;
case (number >= 1001 && number <= 6999):
validated = true;
error = false;
break;
case (number >= 8001 && number <= 34999):
validated = true;
error = false;
break;
case (number >= 36001 && number <= 37999):
validated = true;
error = false;
break;
default:
console.log("error");
error = true;
}
But I quickly realised this would be a stupid long code.
What would be a better way to validate all the ranges of postal codes?

You can reduce your switch for something like this
switch (true) {
case ($(this).val().length < 5) :
console.log("not filled out");
break;
case (number >= 1001 && number <= 6999):
case (number >= 8001 && number <= 34999):
case (number >= 36001 && number <= 37999):
validated = true;
error = false;
break;
default:
console.log("error");
error = true;
}
You can then add the list of rules you need

Related

Any particular reason why this switch-case statement in js is returning undefined?

Here is my code. I have cross checked with online docs and couldn't find any reason for this to not work.
let marks = 90;
switch (marks) {
case 1:
if (marks <= 100 && marks >= 80) {
console.log("Very Good");
}
break;
case 2:
if (marks >= 60 && marks <= 79) {
console.log("Good");
}
break;
case 3:
if (marks >= 30 && marks <= 59) {
console.log("Can do better");
}
break;
case 4:
if (marks < 30) {
console.log("Fail");
}
break;
}
let marks = 90;
switch (marks<=100) {
case marks <= 100 && marks>=80:
console.log("Very Good");
break
case ( marks >=60 && marks <= 79) :
console.log("Good")
break;
case (marks >= 30 && marks <=59):
console.log("Can do better");
break;
case (marks < 30) :
console.log("Fail");
break;
}
This should work your switch cases don't make sense

Someone could explain what is happening with the code?

I want to guess what type of letter the user types down.
var userLetter = prompt("Enter a letter and I will tell you what type of letter is","Enter here, wish me luck!");
function selectUserLetter(letter) {
var returnType = "NA";
if (userLetter.charCodeAt(0) >= "A".charCodeAt(0) && userLetter.charCodeAt(0) <= "Z".charcodeAt(0)) {
returnType = "U";
}
else if (userLetter.charCodeAt(0) >= "a".charCodeAt(0) && userLetter.charCodeAt(0) <= "z".charcodeAt(0)) {
returnType = "L";
}
else if (userLetter.charCodeAt(0) >= "0".charCodeAt(0) && userLetter.charCodeAt(0) <= "9".charcodeAt(0)) {
returnType = "N";
}
return returnType;
}
switch (selectUserLetter(userLetter)) {
case "U":
document.write("Your letter is Uppercase");
break;
case "L":
document.write("Your letter is Lowercase");
break;
case "N":
document.write("Your letter is a number");
break;
default:
document.write("You typed anything else");
}
In your code, fragments "Z".charcodeAt, "z".charcodeAt(0) and "9".charcodeAt(0) consist of charcodeAt function call. The thing is that JavaScript is case sesitive langauge. So, charcodeAt doesn't exists rather then charCodeAt.

Switch case failing, returns NaN [duplicate]

This question already has answers here:
JavaScript conditional switch statement
(5 answers)
Closed 7 years ago.
I have a bmi calculator and converted the conditionals to a switch statement to make it a bit cleaner. However, now the code is breaking and not causing the var result to be set so it can be displayed.
Any ideas what I am missing here?
JS
$('#calculatebutton').click(function () {
var weight = parseInt($('#weight-lb').val()),
heightInches = parseInt($('#height-ft').val()) + parseInt($('#height-in').val()),
heightsqaured = (heightInches) * (heightInches),
result = ((weight) / (heightsqaured) * 703);
switch(result) {
case (result < 16):
var rating = 'You are severely underweight';
break;
case (result > 16) && (result < 18.5):
var rating = 'You are underweight';
break;
case (result > 18.5) && (result < 25):
var rating = 'You are healthy';
break;
case (result > 25) && (result < 30):
var rating = 'You are overweight';
break;
case (result > 30) && (result < 35):
var rating = 'You are moderately obese';
break;
case (result > 80):
var rating = 'This result seems unlikely, please check that the information you have entered is correct';
break;
}
$('#result').html('Your BMI is ' + result.toFixed(1) + '. ' + rating + '.');
});
JS Fiddle
http://jsfiddle.net/o12xpy2s/
Change:
switch(result) {
...to:
switch(true) {
Your switch cases are all true or false conditions. So set your switch expression switch(expression) to one or the other. Here you're looking for the true condition of the listed cases.

Password strength function return only one vlaue [closed]

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".

JavaScript - how to validate field to allow certain character and certain length

I need to validate a textbox, so it's value consist of 10 characters (not more, not less). The below code does it, allowing me to set the restricted length for each field separately.
function charLength(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
alert("Invalid number of characters");
elem.focus();
return false;
}else{
return true;
}
}
and this is how I'm calling it:
onBlur="charLength(document.getElementById('tf1'),1,9)"
but the field that I validate must not only be 10 characters long, but it also has to start with letter Z.
How would I do such validation? is it possible in the first place?
try it also:
function charZ10(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max && uInput.substr(0, 1) == "Z"){
alert("Material number has to consist of 10 characters begining with Z");
elem.focus();
return false;
}
else return true; //i
}
and try to add maxlength in the textbox
<input type="text" maxlength="10">
function charZ10(elem, min, max){
var uInput = elem.value;
if(uInput.length == 10 && uInput.substr(0, 1) == "Z")
return true;
alert("Material number has to consist of 10 characters begining with Z");
elem.focus();
return false;
}
function charZ10(elem) {
var pass = /^Z.{9}$/.test(elem.value); // 10 chars starting with Z
if (!pass) {
alert("Try again, noob.");
elem.focus();
}
return pass;
}
Must be
if(uInput.length <= 10 && substr(uInput,0, 1) == "Z")

Categories

Resources