bhushan143
bhushan143

Reputation: 11

regex to allow any character but need to accept only single space for entire textbox using javascript

I am trying to validate a text box which needs to accept any character but needs to accept only single whitespace for entire text box field but not start with whitespace character.

Example:

"wall heel" & "wall " & "wall"

Here i am posting my code:

var alpha = (/^\w+ +\w*$/)||(/^\w*$/);

Note:Here it only accepts the characters like "wall heel" but not accepts "wall".

Please suggest me some codes.

Upvotes: 0

Views: 636

Answers (4)

gp.
gp.

Reputation: 8225

use this regex

/^[^\s]+([\s]([^\s]+)?)?$/

This will match everything except:

  • whitespaces in the beginning (space, tab, new line etc)
  • more than 1 whitespaces in total.

Upvotes: 0

Mulan
Mulan

Reputation: 135217

I think this does the trick for you

/^[^ ]+(?: [^ ]+)?$/

See it here on regex101

enter image description here

Upvotes: 3

alpha bravo
alpha bravo

Reputation: 7948

use this pattern ^[^ ](?!(.*? ){2}).*$
Demo

  • ^[^ ] start with a non space character.
  • (?! negative lookahead.
  • (.*? ){2} two spaces
  • ) end of lookahead
  • .*$ followed by anything to the end

Upvotes: 1

Fabricator
Fabricator

Reputation: 12772

Make sure it is either empty, or does not start with space and have fewer than 2 spaces.

var valid = (s == "" || (s[0] != " " && s.split(" ").length < 2));

Upvotes: 0

Related Questions