Jump to content
Larry Ullman's Book Forums

Weird Things Happening With Zipcode Validator

Recommended Posts

Hi everyone,


So, I am doing the zip code validator on the text:


var regexp = /^\d{5}(-\d{4})?$/;

regexp.test (15265-5325)


returns false



var regexp = /^\d{5}(-\d{4})?$/; // same code

regexp.test (15265-3325)


returns true


I have realized that unless the first number after the hyphen is less than 4, the expression will return false.


I tried putting ^ inside parenthesis with first (). Fixes error. But if the first digit is 1 or 0 returns false.


>>> var regexp = /(^\d{5})(-\d{4})?$/; regexp.test (85265-5325)




>>> var regexp = /(^\d{5})(-\d{4})?$/; regexp.test (15265-5325)




>>> var regexp = /(^\d{5})(-\d{4})?$/; regexp.test (05265-5325)





Anyone has any idea why is this happening???



var regexp = /^(\d{5})(-\d{4})?$/;


Link to comment
Share on other sites

Make sure you put your actual data being testing within quotes to make it a string.


I just ran the following and got true for all instances:


<!DOCTYPE html>

<html lang="en">


   <meta charset="UTF-8">

   <title>JS regex test</title>




     var regex = /^\d{5}(-\d{4})?$/;

     alert(regex.test('15265-5325')); // true

     alert(regex.test('15265-3325')); // true

     alert(regex.test('85265-5325')); // true

     alert(regex.test('05265-5325')); // true




  • Upvote 1
Link to comment
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.
Note: Your post will require moderator approval before it will be visible.

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.


  • Create New...