javascript - Regex to allow numbers and digits but only one comma -


i have task user should able edit first line of address field should able use 1 comma can put 1 comma anywhere in string.

i wondering if there way done in javascript?

so far have tried:

^[a-za-z0-9\&\-\,\.\/\'_ ]+$ 

but regex allows me enter multiple commas.

so want regex allow user this:

21, tash place n13 2ij

or this: ,tash place 21 n13 2ij

but not this:

21, tash place, n13, 2ij

any appreciated

you may use

/^[-a-za-z0-9&.\/'_ ]*(?:,[-a-za-z0-9&.\/'_ ]*)?$/ 

see regex demo.

here,

  • ^ - matches start of string,
  • [-a-za-z0-9&.\/'_ ]* - matches 0+ letters, digits or -./'_ symbols, then
  • (?:,[-a-za-z0-9&.\/'_ ]*)? - optional sequence (1 or 0 occurrences) of:
    • , - comma (thus, 1 allowed)
    • [-a-za-z0-9&.\/'_ ]* - matches 0+ letters, digits or -./'_ symbols, then
  • $ - end of string.

another way add (?!(?:[^,]*,){2}) negative lookahead regex:

/^(?!(?:[^,]*,){2})[-a-za-z0-9&.\/',_ ]+$/   ^^^^^^^^^^^^^^^^^ 

see another regex demo

the (?!(?:[^,]*,){2}) lookahead fail match if there 2 sequences of 0+ chars other , , , in string.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -