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

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

javascript - Only empty spaces should not be allowed in the input field

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...