1

I have a text area and a user can input US zip codes in it separated by a comma or (comma and space).

It could be like 12345,45678, 89654

The following regex is working and is removing not allowed characters:

$object.val($object.val().replace(/[^\d\, ]/g, ''));

I would like to enhance it, so that

  1. i always should have 5 digits in the beginning
  2. after 5 digits, there should be a comma or comma and space
  3. comma or (comma and space) should not be at the very end of the string. It must be 5 digit number at the end.

This needs to tackle the copy paste as well. The user may copy paste invalid length for the zip code.

Thanks

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
learning...
  • 3,104
  • 10
  • 58
  • 96
  • 1
    Have you thought about the jQuery maskedinput plugin? It works great for me, and I've had no conflicts. http://digitalbush.com/projects/masked-input-plugin/ – TimSPQR Sep 27 '13 at 14:56
  • have you tried searching SO for possible answers that could help you accomplish this? how about the one here - http://stackoverflow.com/questions/160550/zip-code-us-postal-code-validation/160583#160583 – Zathrus Writer Sep 27 '13 at 14:57
  • Instead of cropping input texts, I would recommend just to show when they are invalid. – Bergi Sep 27 '13 at 14:58
  • You are ignoring the new 9 digit (preferred) zip code:12345-5432 . Is that a good idea? – Floris Sep 27 '13 at 14:58

3 Answers3

2

Use this regex: ^\d{5}(, ?\d{5})*$

It specifies 5 digits at the beginning: ^\d{5} and any number of other comma, space, and 5 digit combinations: (, ?\d{5})*

Brian Stephens
  • 5,161
  • 19
  • 25
1

You can use:

var s='12345,45678, 12345';
var m = s.match(/^(?:\d{5},\s?)*\d{5}$/);
anubhava
  • 761,203
  • 64
  • 569
  • 643
0
<html>
    <head>
        <title></title>
        <script type="text/javascript">
            function Validate(txt) {
                txt.value = txt.value.replace(/[^, 0-9]+/g, '');
            }
        </script>
    </head>
    <body>
        <form>
            <input type = "text" id ="txt" onkeyup = "Validate(this)" />
        </form>
    </body>
</html>
Draken
  • 3,134
  • 13
  • 34
  • 54
Hrushi
  • 309
  • 3
  • 6