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&.\/',_ ]+$/ ^^^^^^^^^^^^^^^^^ the (?!(?:[^,]*,){2}) lookahead fail match if there 2 sequences of 0+ chars other , , , in string.
Comments
Post a Comment