i need validate below format using jquery/javascript regex validation.
it done in java regex using code :
"(\\d{1,2})?\\s?\\[\\d{3}\\]\\s?\\d{4}-?\\d{4}"
but require in javascript/jquery @ client side.
below samples :
1) 1 [123] 1234-5678 2) 1[123] 1235-5678 3) 1[123]1236-5678 4) 1 [123]1237-5678 5) 1 [123] 12385789 6) 1[123]12341678 7) 1 [123]12345678 8) 1[123] 1234-5678 9) [123] 1234-5678 10) [123]1234-5678 11) [123]12345678 12) [123] 12345678
its combination of number, square brackets, dash, here number & square bracket must exist dash(-) may or may not.
only number & square brackets can allowed, no else characters
any appreciated.
in js, can use regexp object literal means don't need escape backslash characters. regexp object literal can created surrounding regex expression 2 forward slash characters:
original regex:
"(\\d{1,2})?\\s?\\[\\d{3}\\]\\s?\\d{4}-?\\d{4}"
assigning variable regexp object in javascript:
var myregex = /(\d{1,2})?\s?\[\d{3}\]\s?\d{4}-?\d{4}/;
any flags want add regex (g, i, m, y) should go directly after terminating forward slash. ex:
/(\d{1,2})?\s?\[\d{3}\]\s?\d{4}-?\d{4}/gm
another way of doing take original regex in string form , pass regexp constructor, recommended dynamic regular expressions instead of static ones:
var myregex = new regexp('(\\d{1,2})?\\s?\\[\\d{3}\\]\\s?\\d{4}-?\\d{4}');
you can optionally pass in second argument constructor takes string of flags.
more documentation on creating , using regexp objects can found here.