1

I want to prevent 2 spaces from being entered consecutively. Right now, for a name, you can use all spaces. I want multiple words with 1 space in-between each word, but not more than 1 space together. Also, possibly even prevent multiple spaces if the text was copied and pasted in?

I force 3 characters but they can all be spaces in my form unless I use this code but it stops all spaces. I want to allow only 1 space between words. :

<input type="text" name="name" placeholder="Required...." 
  minlength="3" maxlength="40" required 
  oninvalid="this.setCustomValidity('Please enter a name with at least 3 characters.')" 
  oninput="setCustomValidity('')" 
  onKeyDown="javascript: var keycode = keyPressed(event); if(keycode==32){ return false; }" 
/>

I found a way to stop all spaces but I lost the code trying other things. I could find it again but it is not exactly what I want. I know there must be a simple way, and I can't be the only one who wants it. Can someone please help me?

Geshode
  • 3,600
  • 6
  • 18
  • 32
  • 1
    Does this answer your question? [Regex to replace multiple spaces with a single space](https://stackoverflow.com/questions/1981349/regex-to-replace-multiple-spaces-with-a-single-space) – Simone Rossaini Jun 06 '23 at 09:26
  • Mine it's just an example, if you try to input/paste double character you will see the script doesn't allow. (we r not coding service) – Simone Rossaini Jun 07 '23 at 12:39
  • I got it to erase spaces using the link above! :D Thanks! but it affects the 3 character minimum for input (sucks for the name) they can keep pressing the space and it counts the spaces it removes. any idea how can I fix that? – Antarctica-UFO Jun 07 '23 at 14:05
  • the code I used is in the "Comprehensive unencrypted answer for newbies et al" answer – Antarctica-UFO Jun 07 '23 at 14:18
  • even though I can't get the consecutive spaces to be prevented without counting the spaces towards the forms minlength, I still made a solid form that works really well using 2 names disabling all spaces which does not mess up the count either. I used the no space combined with the following simple html code in the input to force a valid email: pattern="^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$" now if I could force no consecutive spaces using a similar code? can anyone help me – Antarctica-UFO Jun 08 '23 at 05:03

1 Answers1

1

As you can see from my example the code i linked work with oninput too

document.querySelector('input').addEventListener('input', (e) => {
   e.target.value = e.target.value.replace( /  +/g, ' ' );
});
document.querySelector('input').addEventListener('change', (e) => {
   e.target.value = e.target.value.replace( /  +/g, ' ' );
});
<input type="text">
Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34