Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a regex /^([A-Za-zs-']{1,})$/

This accepts alphabets, hyphen and apostrophes.

  1. Having multiple spaces at the beginning of the string,in the middle and the end of the string is fine.
  2. "Henry - Jackson's Derby-'s" is also correct

I have only one problem to be fixed in this regex.

"If I enter only empty spaces in the input field it accepts that as well" - which is wrong

How can I avoid this?

question from:https://stackoverflow.com/questions/65937012/only-empty-spaces-should-not-be-allowed-in-the-input-field

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
113 views
Welcome To Ask or Share your Answers For Others

1 Answer

You are allowing at least one of any character in the square brackets like that, including spaces, so even the string " " would be accepted.

You should do something like: /^s*([A-Za-z-']+[A-Za-z-'s]*)s*$

  1. ^s*: initial spaces allowed
  2. [A-Za-z-']+: at least one character in the given set (omit the space here so you have at least one character that is not a space)
  3. [A-Za-z-'s]*: zero or more characters in the given set
  4. s*$: trailing spaces and end of the string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...