1

Basically my validation is very simple, but I'm totally new to regex and need this fired up fairly quickly, so here goes: 1234567890 or 123456-7890 it can be, obviously, any number in a range of 0 - 9 and the length must be either 10 or 11 characters.

Can you please show me a way to write a function for this?

Xeen
  • 6,755
  • 14
  • 53
  • 106
  • see this stack overflow post http://stackoverflow.com/questions/4840547/javascript-regular-expression-to-match-x-digits-only – Sachin Gupta Apr 01 '15 at 06:15

3 Answers3

2

It's hard to post using an iPhone, but, here it goes:

/^\d{6}-?\d{4}$/
  • ^ - starts with
  • $ - ends with
  • \d{6} - match 6 digits
  • ? - something is optional, in this case -
  • \d{4} - match 4 digits

So, the above would match 123456-7890 and 1234567890

lshettyl
  • 8,016
  • 4
  • 23
  • 30
1
function isId(id) {
    return /^\d{6}-?\d{4}$/.test(id);
}

isId("1234567890"); // true
isId("123456-7890"); // true
Timur Osadchiy
  • 4,911
  • 2
  • 22
  • 26
0

If the dashes should be possible at any position:

function test_id(id) {return /^\d{10,11}$/.test(id.replace(/-/g, ''));}

Output:

test_id('123')
> false
test_id('2')
> false
test_id('223-345-123-12')
> true
test_id('223-345-12312')
> true
Oleg K.
  • 1,529
  • 8
  • 11