Reputation: 1273
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
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 includedSee 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
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
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