views:

35

answers:

1

I need to write some Javascript to check an input to only allow number and letter and '-' and '_' and space bar.

Here is my regular expression

var pattern = /^([a-zA-Z])([a-zA-Z0-9_-]){1,80}$/;

Above regex does not include space bar. How can I add space bar condition into my regex.

+2  A: 

For me this:

var pattern = /^([a-zA-Z])([a-zA-Z0-9_ -]){1,80}$/;

works.

Maybe you ran into the issue with trying it like this ?

var pattern = /^([a-zA-Z])([a-zA-Z0-9_- ]){1,80}$/;

and the regex Parser thought you ment "underscore to spacebar" and not "underscore dash and spacebar ? (Didn't test that)

Edit

Did a little testing

<script>
alert(/^([a-zA-Z])([a-zA-Z0-9_-]){1,80}$/.test("Aa232423"));
// true
alert(/^([a-zA-Z])([a-zA-Z0-9_ -]){1,80}$/.test("Aa232 423"));
// true 
alert(/^([a-zA-Z])([a-zA-Z0-9_- ]){1,80}$/.test("Aa232423"));
// parser error: invalid range in character set
</script>

Do i guess i was right with my assumption ;)

Secound Edit in Response to OPs Comment:

<script>
alert(/^([a-zA-Z])([a-zA-Z0-9_ -]){1,80}$/.test("Aa232-423"));
//true
alert(/^([a-zA-Z])([a-zA-Z0-9_ -]){1,80}$/.test("Aa232-42 3"));
//true
</script>
edorian
Even though your `-` is at the end of the set, I'd still suggest you escape it so you can be 100% sure you don't run into problems.
casablanca
Thanks for the addition casablanca, +1
edorian
@edorian and how can replace spacebar with '-'
Giffary
@Giffary edited my answer
edorian
@edorian how can replace spacebar with '-' i use var text = res_name.val().replace('/\s+/', '-'); it's not work
Giffary