Skip to content Skip to sidebar Skip to footer

Prevent More Than One Space Between Words

I have a function that prevents people putting numbers or any symbol but letters onkeypress into a text box due to ongoing problems with data entry.

Solution 1:

Neglecting all the other helpful suggestions and comments and strictly following the OP's requirements one has to ...

  1. Adapt the return condition in a way that takes into account if, with the current keystroke, a whitespace sequence is going to be created.
  2. Thus one has to implement a method that determines exactly that.
  3. There might be some possible helper methods too.
  4. code example ...

functionisWhiteSpace(char) {
  return (/\s/).test(char);
}
functionwillCreateWhitespaceSequence(evt) {
  var willCreateWSS = false;
  if (isWhiteSpace(evt.key)) {
  
    var elmInput = evt.currentTarget;
    var content = elmInput.value;

    var posStart = elmInput.selectionStart;
    var posEnd = elmInput.selectionEnd;

    willCreateWSS = (
         isWhiteSpace(content[posStart - 1] || '')
      || isWhiteSpace(content[posEnd] || '')
    );
  }
  return willCreateWSS;
}

functionisAlfa(evt) {

  evt = (evt || window.event);
  var charCode = (evt.which || evt.keyCode);

  return ((
       (charCode > 32)
    && (charCode < 65 || charCode > 90)
    && (charCode < 97 || charCode > 122)

  ) || willCreateWhitespaceSequence(evt)) ? false : true;
}
<inputtype="text"name="name"onkeypress="return isAlfa(event)"/>

Solution 2:

may be try to use something like this. on your keypress event try to check the last value by using stringsubstr method and if that gives you a space and current code is also a Space then prevent or do whatever you want to do with input.

functioncheckstuff(event){
  if (event.target.value.substr(-1) === ' ' && event.code === 'Space') {
    console.log('space pressed in sequence');
  }
}
<inputtype='text'onkeypress="checkstuff(event)">

Solution 3:

Rather than listening for and evaluating each key press it would be far simpler just to react to any and all input and then sanitise whatever was entered via a RegExp.

Example:

<inputtype=textid=myfield />

JS:

document.querySelector('#myfield').addEventListener('input', evt => {
    evt.target.value = evt.target.value.replace(/[^a-z\s]/ig, '').replace(/\s{2,}/g, ' ');
});

That first replaces all non-letters and spaces with nothing, then replaces sequences of 2 or more spaces with a single space.

Post a Comment for "Prevent More Than One Space Between Words"