Jump to content
Larry Ullman's Book Forums
Sign in to follow this  
rafaec

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)

 

true

 

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

 

false

 

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

 

false

 

 

Anyone has any idea why is this happening???

 

 

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

-

Share this post


Link to post
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">

 <head>

   <meta charset="UTF-8">

   <title>JS regex test</title>

 </head>

 <body>

   <script>

     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

   </script>

 </body>

</html>

  • Upvote 1

Share this post


Link to post
Share on other sites

I was running them in Firebug console...also tried it in Chrome console...same issue.

 

But you are right, when you run the whole code like that it works.

 

Anyone have any idea why do you get such an error in console???

Share this post


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.
Note: Your post will require moderator approval before it will be visible.

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...
Sign in to follow this  

×
×
  • Create New...