Harish
Harish

Reputation: 1273

Regular expression for name with spaces allowed in between the text and avoid spaces when there is no text

Hello I'm trying to write a regular expression for user name in my form.

The regular expression should allow spaces and . when the text is written

Ex : S. Harish Kumar

Check the regEx that I have written so far

^[a-zA-Z\s\.]*$

The above regEx also accepts any string with just spaces and . which I don't want. Can you help me with the perfect regEx which doesn't accept spaces and . when no text is entered?

Thanks in advance :)

Upvotes: 4

Views: 26281

Answers (3)

Alessandro
Alessandro

Reputation: 4472

You could use ^[a-zA-Z].*[\s\.]*$

  • ^[a-zA-Z] asserts string starts with a char (a-zA-Z)
  • .*[\s\.]*$ followed by any char dot and spaces included

See following example:

var regex = /^[a-zA-Z].*[\s\.]*$/g;


function check(par){
  console.log(par.value + " match: " + regex.test(par.value));
}
Name <input type="text" id="test" value="" onchange="javascript:check(this)">

Upvotes: 1

Dmitry Egorov
Dmitry Egorov

Reputation: 9650

I would say a name is a sequence of alphabetic chars delimited by spaces or dots, which can be defined by the following regex:

^[a-zA-Z]+(?:[\s.]+[a-zA-Z]+)*$

Demo: https://regex101.com/r/rH5jtc/2

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626893

Just disallow a string that only consists of whitespaces/dots:

^(?![\s.]+$)[a-zA-Z\s.]*$
 ^^^^^^^^^^^ 

See the regex demo.

The (?![\s.]+$) is a negative lookahead that fails the match if the whole string contains whitespace or dot chars only.

Upvotes: 9

Related Questions