Philipp M
Philipp M

Reputation: 3488

Clientside validation for regex - allowing whitespace in middle but not beginning and end

I'm allowing whitespace for this regex like this:

javascript:

var re_username = /^[a-zA-Z\040\.\-]+$/;
var is_username = re_username.test($('#chatusername').val());
console.log(is_username);   

... but I want to disallow it at the beginning and at the end. This worked:

javascript:

var re_username = /^[a-zA-Z]+[a-zA-Z\040\.\-]+[a-zA-Z\.]+$/;

... but I need to enter at least 3 (<3 digits returns false although I enter e.g. A) digits for the regex to return true which causes trouble adding classes and stuff ...

I've found this for this allowing whitespaces at the beginning and end

javascript:

var re_username = /^\S+(?: \S+)*$/

But it's allowing all characters ... . How can I match my targeted regex? I tried this ... but it already didn't work ..

var re_username = /^\S+([a-zA-Z]\040\S+)*$/; 

Upvotes: 3

Views: 132

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626835

Use

var re_username = /^[a-zA-Z.-]+(?:\040+[a-zA-Z.-]+)*$/;

It will match

  • ^ - start of string
  • [a-zA-Z.-]+ - 1+ letters, . and -
  • (?:\040+[a-zA-Z.-]+)* - 0+ sequences of
    • \040+ - 1+ regular spaces
    • [a-zA-Z.-]+ - 1+ letters, . and -
  • $ - end of string

See the regex demo.

NOTE: if you do not want to allow consecutive multiple spaces, remove the + after \040.

Another, less efficient way, is via lookaheads:

var re_username = /^(?!\040|.*\040$)[a-zA-Z\040.-]+$/;
                    ^^^^^^^^^^^^^^^ 

Here, the (?!\040|.*\040$) negative lookahead will fail the match if a space is found right at the start of a string or after any 0+ chars (.*) at the end of the string ($).

Upvotes: 1

Related Questions