Jump to content

Determine variable type


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 post
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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...