JonH JonH - 2 months ago 5
Javascript Question

Allow space in regex when validating file

I've got a text box where I wanted to ensure some goods and bads out of it.

For instance good could include:


Some bad things I did not want to include was:


But one thing I wanted to allow would be to allow spaces between words so this should of been good:

Good String

However my regex/js is stating this is NOT a good string - I want to allow it. I'm using the test routine for this and I'm as dumb as you can get with regexes. I don't know why I can never understand these things...

In any event my validation is as follows:

var rx = /^[\w.-]+$/;
if (!rx.test($("#MainContent_txtNewDocumentTitle").val())) {
//code for bad string
//code for good string

What can I do to this:

var rx = /^[\w.-]+$/;

Such that spaces are allowed?


You can use this regex instead to allow space only in middle (not at start/end):

var rx = /^[\w.-]+(?:[ \t]+[\w.-]+)*$/gm;

RegEx Demo

RegEx Breakup:

^             # line start
[\w.-]+       # match 1 or more of a word character or DOT or hyphen
(?:           # start a non-capturing group
   [ \t]+     # match one or more space or tab
   [\w.-]+    # match 1 or more of a word character or DOT or hyphen
)*            # close the non-capturing group. * will allow 0 or more matches of group
$             # line end
/gm           # g for global and m for multiline matches

RegEx Reference