rafaec Posted September 13, 2012 Share Posted September 13, 2012 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})?$/; - Link to comment Share on other sites More sharing options...
HartleySan Posted September 14, 2012 Share Posted September 14, 2012 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> 1 Link to comment Share on other sites More sharing options...
rafaec Posted September 14, 2012 Author Share Posted September 14, 2012 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??? Link to comment Share on other sites More sharing options...
HartleySan Posted September 14, 2012 Share Posted September 14, 2012 Like I asked before, are you running the zip codes through as strings (i.e., with quotes)? Link to comment Share on other sites More sharing options...
rafaec Posted September 14, 2012 Author Share Posted September 14, 2012 Just realized that...thanks! Link to comment Share on other sites More sharing options...
Recommended Posts