How to check a postal code in JavaScript?
Your slice()
is not taking all four numbers of the postal code. Instead, use the following postalCode.slice(0, 4)
.
Have a look at the Mozilla docs regarding slice
.
In the working code snippet below also note the following three lines.
var postalCodeC = Number(postalCode.slice(0, 4));
// converts the alphanumeric value from prompt to a number for better comparison.
var postalCodeL = postalCode.slice(-2).toUpperCase();
// converts the letters of the postal code to CAPS, this way Aa, AA or aa will be valid too.
var correctCity = city.toLowerCase() === 'amsterdam';
// the same here, convert city to lowercase letters and compare the input to 'amsterdam'
Working example.var sendingCost = 15;var city = prompt("What city do you live in?");var postalCode = prompt("What is your postal code?");var postalCodeC = Number(postalCode.slice(0, 4));var postalCodeL = postalCode.slice(-2).toUpperCase();
var correctCity = city.toLowerCase() === 'amsterdam';var withinPostalArea = postalCodeC >= 1000 && postalCodeC <= 2000 && postalCodeL >= 'AA' && postalCodeL <= 'BB';
console.log(postalCodeC);console.log(postalCodeL);
if (correctCity && withinPostalArea) { alert('There is no sending cost');} else { alert('The sending cost is €' + sendingCost);};
JavaScript regex to validate postal code or City
You can use a pipe in your regex, which acts like an OR.
Example snippet:
function validateCityOrPostalCode(value) { return /^([0-9]{5}|[a-zA-Z][a-zA-Z ]{0,49})$/.test(value);}
var values = ['12345','New York','1234','',' ','Boston33','333Chicago'];
values.forEach( function(value) { console.log(value +":"+ validateCityOrPostalCode(value));});
Checking Postal Codes with JQuery
The problem is within the logic of your loop. The loop will only run one time, because the loop will always return after the first iteration (true if it finds the first element in the list array, false for everything else), rather than continuing through all iterations. So, what is happening for the second element is that the loop is running, determining that the first element was not found and returning false and never even processing the second element.
A better way to do this would be to loop the list array until you find a matching element, and keep track of wether an match was found or not. This will make sure we don't drop out of the loop until we've processed all elements of the array (or found a match, in which case we can stop the loop to save on processing).
See below (http://jsfiddle.net/ryanbrill/Kws7A/) for some example code with a few comments about what is happening.
$(document).ready(function(){
var list = ['83512','83533'];
$("#checkplz").submit(function() {
var matched = false; // Set up variable to track if we find a match
$(list).each(function() {
// Inside the jQuery 'each' method, 'this' equals the current item in the iteration.
if(this == $("#plz").val()) {
matched = true; // set the 'matched' variable to true
$("#output").append("<strong class='success'>success!</strong>").show();
return; // Since we found a match, we can stop processing the array
}
});
// Outside of the loop, only display no success if we didn't find any matches.
if (!matched) {
$("#output").text("no success!").show().fadeOut(10000);
}
});
});
ZIP Code (US Postal Code) validation
Javascript Regex Literal:
US Zip Codes: /(^\d{5}$)|(^\d{5}-\d{4}$)/
var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test("90210");
Some countries use Postal Codes, which would fail this pattern.
How to validate postcode in a form using JavaScript
You can do something like this:
function validatePostalCode(){
var regExp = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})$/;
var postcode = document.getElementById("postcode").value;
if( regExp.test( postcode ) ){
// Do something here, result is true.
} else {
alert("result is false");
}
}
You can try it out in this fiddle: http://jsfiddle.net/Cedriking/5b8wtf1f/2/
Javascript : How to find the position of a zip code in a string?
http://jsfiddle.net/jeffreyTang/8038whkt/
var re = /[0-9]{6}/;
var str = '7 CITE VANEAU - 750007 PARIS';
// get the index of the dash
var dash = str.indexOf('-');
// remove everything before the dash
str = str.substring(dash);
// execute the pattern match
var m = re.exec(str);
// this is your answer
console.log(m[0]);
How can I quickly determine the State for a given zipcode?
US zipcode data is in fact stable enough that you can do this without hitting an API or a database if only State (not the City or anything else) is needed.
Here's a lightweight JS solution that takes a zipcode (as a string), determines the proper US state, and returns the state as its two-letter postal abbreviation.
function getState(zipString) {
/* Ensure param is a string to prevent unpredictable parsing results */
if (typeof zipString !== 'string') {
console.log('Must pass the zipcode as a string.');
return;
}
/* Ensure we have exactly 5 characters to parse */
if (zipString.length !== 5) {
console.log('Must pass a 5-digit zipcode.');
return;
}
/* Ensure we don't parse strings starting with 0 as octal values */
const zipcode = parseInt(zipString, 10);
let st;
let state;
/* Code cases alphabetized by state */
if (zipcode >= 35000 && zipcode <= 36999) {
st = 'AL';
state = 'Alabama';
} else if (zipcode >= 99500 && zipcode <= 99999) {
st = 'AK';
state = 'Alaska';
} else if (zipcode >= 85000 && zipcode <= 86999) {
st = 'AZ';
state = 'Arizona';
} else if (zipcode >= 71600 && zipcode <= 72999) {
st = 'AR';
state = 'Arkansas';
} else if (zipcode >= 90000 && zipcode <= 96699) {
st = 'CA';
state = 'California';
} else if (zipcode >= 80000 && zipcode <= 81999) {
st = 'CO';
state = 'Colorado';
} else if ((zipcode >= 6000 && zipcode <= 6389) || (zipcode >= 6391 && zipcode <= 6999)) {
st = 'CT';
state = 'Connecticut';
} else if (zipcode >= 19700 && zipcode <= 19999) {
st = 'DE';
state = 'Delaware';
} else if (zipcode >= 32000 && zipcode <= 34999) {
st = 'FL';
state = 'Florida';
} else if ( (zipcode >= 30000 && zipcode <= 31999) || (zipcode >= 39800 && zipcode <= 39999) ) {
st = 'GA';
state = 'Georgia';
} else if (zipcode >= 96700 && zipcode <= 96999) {
st = 'HI';
state = 'Hawaii';
} else if (zipcode >= 83200 && zipcode <= 83999) {
st = 'ID';
state = 'Idaho';
} else if (zipcode >= 60000 && zipcode <= 62999) {
st = 'IL';
state = 'Illinois';
} else if (zipcode >= 46000 && zipcode <= 47999) {
st = 'IN';
state = 'Indiana';
} else if (zipcode >= 50000 && zipcode <= 52999) {
st = 'IA';
state = 'Iowa';
} else if (zipcode >= 66000 && zipcode <= 67999) {
st = 'KS';
state = 'Kansas';
} else if (zipcode >= 40000 && zipcode <= 42999) {
st = 'KY';
state = 'Kentucky';
} else if (zipcode >= 70000 && zipcode <= 71599) {
st = 'LA';
state = 'Louisiana';
} else if (zipcode >= 3900 && zipcode <= 4999) {
st = 'ME';
state = 'Maine';
} else if (zipcode >= 20600 && zipcode <= 21999) {
st = 'MD';
state = 'Maryland';
} else if ( (zipcode >= 1000 && zipcode <= 2799) || (zipcode == 5501) || (zipcode == 5544 ) ) {
st = 'MA';
state = 'Massachusetts';
} else if (zipcode >= 48000 && zipcode <= 49999) {
st = 'MI';
state = 'Michigan';
} else if (zipcode >= 55000 && zipcode <= 56899) {
st = 'MN';
state = 'Minnesota';
} else if (zipcode >= 38600 && zipcode <= 39999) {
st = 'MS';
state = 'Mississippi';
} else if (zipcode >= 63000 && zipcode <= 65999) {
st = 'MO';
state = 'Missouri';
} else if (zipcode >= 59000 && zipcode <= 59999) {
st = 'MT';
state = 'Montana';
} else if (zipcode >= 27000 && zipcode <= 28999) {
st = 'NC';
state = 'North Carolina';
} else if (zipcode >= 58000 && zipcode <= 58999) {
st = 'ND';
state = 'North Dakota';
} else if (zipcode >= 68000 && zipcode <= 69999) {
st = 'NE';
state = 'Nebraska';
} else if (zipcode >= 88900 && zipcode <= 89999) {
st = 'NV';
state = 'Nevada';
} else if (zipcode >= 3000 && zipcode <= 3899) {
st = 'NH';
state = 'New Hampshire';
} else if (zipcode >= 7000 && zipcode <= 8999) {
st = 'NJ';
state = 'New Jersey';
} else if (zipcode >= 87000 && zipcode <= 88499) {
st = 'NM';
state = 'New Mexico';
} else if ( (zipcode >= 10000 && zipcode <= 14999) || (zipcode == 6390) || (zipcode == 501) || (zipcode == 544) ) {
st = 'NY';
state = 'New York';
} else if (zipcode >= 43000 && zipcode <= 45999) {
st = 'OH';
state = 'Ohio';
} else if ((zipcode >= 73000 && zipcode <= 73199) || (zipcode >= 73400 && zipcode <= 74999) ) {
st = 'OK';
state = 'Oklahoma';
} else if (zipcode >= 97000 && zipcode <= 97999) {
st = 'OR';
state = 'Oregon';
} else if (zipcode >= 15000 && zipcode <= 19699) {
st = 'PA';
state = 'Pennsylvania';
} else if (zipcode >= 300 && zipcode <= 999) {
st = 'PR';
state = 'Puerto Rico';
} else if (zipcode >= 2800 && zipcode <= 2999) {
st = 'RI';
state = 'Rhode Island';
} else if (zipcode >= 29000 && zipcode <= 29999) {
st = 'SC';
state = 'South Carolina';
} else if (zipcode >= 57000 && zipcode <= 57999) {
st = 'SD';
state = 'South Dakota';
} else if (zipcode >= 37000 && zipcode <= 38599) {
st = 'TN';
state = 'Tennessee';
} else if ( (zipcode >= 75000 && zipcode <= 79999) || (zipcode >= 73301 && zipcode <= 73399) || (zipcode >= 88500 && zipcode <= 88599) ) {
st = 'TX';
state = 'Texas';
} else if (zipcode >= 84000 && zipcode <= 84999) {
st = 'UT';
state = 'Utah';
} else if (zipcode >= 5000 && zipcode <= 5999) {
st = 'VT';
state = 'Vermont';
} else if ( (zipcode >= 20100 && zipcode <= 20199) || (zipcode >= 22000 && zipcode <= 24699) || (zipcode == 20598) ) {
st = 'VA';
state = 'Virginia';
} else if ( (zipcode >= 20000 && zipcode <= 20099) || (zipcode >= 20200 && zipcode <= 20599) || (zipcode >= 56900 && zipcode <= 56999) ) {
st = 'DC';
state = 'Washington DC';
} else if (zipcode >= 98000 && zipcode <= 99499) {
st = 'WA';
state = 'Washington';
} else if (zipcode >= 24700 && zipcode <= 26999) {
st = 'WV';
state = 'West Virginia';
} else if (zipcode >= 53000 && zipcode <= 54999) {
st = 'WI';
state = 'Wisconsin';
} else if (zipcode >= 82000 && zipcode <= 83199) {
st = 'WY';
state = 'Wyoming';
} else {
st = 'none';
state = 'none';
console.log('No state found matching', zipcode);
}
return st;
}
You can return the state's full name instead of just the two-letter abbreviation by returning state
instead of st
on the last line.
Many thanks to @kevin-boucher and @abaldwin99 for help on parsing smaller New England codes and avoiding the dreaded octal evaluation bug with their answers here.
Also thanks for much of the original code goes to this useful page.
Related Topics
How to Load Content of Page Without Refreshing the Whole Page
Remove Duplicate Objects from Json Array
How to Create a Remember Me Function in Login Without Using Form in JavaScript or Jquery
How to Stop Parsefloat() from Stripping Zeroes to Right of Decimal
Count the Number of Times a Same Value Appears in a JavaScript Array
How to Add Scroll Event in React Component
Jquery Do Not Allow Alphabets to Be Entered in Input Field
Make Redirect to New Url But Remove Previous from History
Reload Table After Deleting an Item from It With React
How to Show an Alert After Reloading the Page in JavaScript
Executing Nodejs Script File in PHP Using Exec()
Assigning Id to All Elements of a Page in Angular Automatically
One Time Page Refresh After First Page Load
Onclick Table Row With Onclick Button and Bootstrap Modal Inside
Generate Child Row Under a Parent Row in HTML Table
How to Wait Until All JavaScript Files Are Loaded Before Executing JavaScript Code
Javascript to Check for Event Without Page Refresh
How to Close an Open Collapsed Navbar When Clicking Outside of the Navbar Element in Bootstrap 3