Jump to content

Determine variable type


grippat

Recommended Posts

I have a form field where the user enters in data which can either be a county or a zip code. If they enter in a county (text) I want the script to preform a different action than it would if they entered in a zip code (numbers). I tried using the typeof() function but that doesn't seem to do what I'm looking for, it considers both to be strings. Is there a way I can determine if the data they entered was a zip code or a county? Thanks!

Link to comment
Share on other sites

Check out regular expressions. http://www.regular-expressions.info/

var uszipreg = /[0-9]{5}(-[0-9]{4})?/;var input = document.getElementById("CountryOrZip").value;if(input.match(uszipreg)){	alert("Thanks for entering in a ZIP code.");}else{	alert("Are you really from the country called " + input + "?");}

Link to comment
Share on other sites

Yeah, regular expressions are a bit daunting at first. Once you understand them, even if it's just a basic understanding, they can really come in handy for stuff like this.Just so you know, the square brackets describe a set of characters to match. So [0-9] would match any single number, from 0 through 9. The curly braces describe how many times to match that character. So [0-9]{5} would match any string that had 5 consecutive numbers.The parentheses set up a group, which, among other powerful things, simply sets aside a piece of the expression as a group. So (-[0-9]{4}) would match "-4453" or "-3325". Adding a question mark to the end of that makes it optional.Something that I didn't include in the original post, which probably should be included is that the expression /[0-9]{5}(-[0-9]{4})?/ would match the following strings:9820955741-2345This is a string with numbers 55522. ser32341sesrssSo, to make the example that I gave a little more robust, you might consider adding ^ and $ to it. The ^, when placed at the start of the expression, makes it so that the match must occur at the start of the string. The $, when placed at the end of an expression, makes it so that the match must occur at the end of the string. So, the expression would then look like this:/^[0-9]{5}(-[0-9]{4})?$/I hope this helps.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...