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


  • Create New...