Regex golf, is this a valid PIN?

David Landry dlandry at byu.net
Mon Feb 24 07:33:04 MST 2014


Javascript, right?

On Mon, Feb 24, 2014 at 5:25 AM, S. Dale Morrey <sdalemorrey at gmail.com>wrote:

> But I don't think it would work in a case where a pin starts with 0 would
> it?
>
For instance would 0123456789 return true or false with this?
>

Well, plugging it in to the Chrome Javascript console gives this:

> isPIN('0123456789')
true

Is there a better regex than this that could also do the trick?
> Is there extra cruft that could or ought to be eliminated? (my regex fu
> sucks bad)
>

There's a little bit of redundancy in there. Also, there's no length
requirement (e.g. isPIN('') also returns true).

Without adding length requirements, I'd do it like this:

  function isPIN(str) {
    return /^\+?(\d*)$/.test(str);
  }

With a length requirement, it might look like this (if PINs must be 4
numbers long, {a,b} for a range from a to b length):

  function isPIN(str) {
    return /^\+?(\d{4})$/.test(str);
  }

---
David Landry


More information about the PLUG mailing list