简体   繁体   中英

Prevent space in input from both text input and copy and paste

I want to prevent the user from entering spaces as well as removing spaces if they paste in text that contains spaces.

Preventing the entry of a space from the keyboard is easy, but I am having issues with removing the spaces from a paste as I want to be able to use the arrow keys to move to any part of the input and change the text and I also need it to be done immediately rather then when the input loses focus.

In the code below it prevents spaces from being entered and removes spaces on paste but the cursor within the input always gets moved to the right preventing you from changing the characters at the beginning unless you just delete all of it and retype.

 <input type="text">

$("input").on("keydown", function (e) {
    return e.which !== 32;
});

$('input').keyup(function(){
    str = $(this).val()
    str = str.replace(/\s/g,'')
    $(this).val(str)
});

http://jsfiddle.net/tgtdrk2o/

In order to accomplish this, we need to define a few functions first. I've used jQuery:

// We need this function if text is pasted arbitrarily.    
$.fn.getCursorPosition = function() {
    var input = this.get(0);
    if (!input) return; // No (input) element found
    if ('selectionStart' in input) {
        // Standard-compliant browsers
        return input.selectionStart;
    } else if (document.selection) {
        // IE
        input.focus();
        var sel = document.selection.createRange();
        var selLen = document.selection.createRange().text.length;
        sel.moveStart('character', -input.value.length);
        return sel.text.length - selLen;
    }
};

// This function will allow us to return to the proper cursor position after a paste.
$.fn.setCursorPosition = function(pos) {
  return this.each(function(index, elem) {
    if (elem.setSelectionRange) {
      elem.setSelectionRange(pos, pos);
    } else if (elem.createTextRange) {
      var range = elem.createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  });
};

$('#nospace').bind('paste', function(event){
    event.preventDefault();
    var clipboardData = event.originalEvent.clipboardData.getData('text/plain');
    str = clipboardData.replace(/\s/g,'');
    var currentCursorPos = $(this).getCursorPosition();
    var output = [$(this).val().slice(0, currentCursorPos), str, $(this).val().slice(currentCursorPos)].join('');
    $(this).val(output);
    $(this).setCursorPosition(currentCursorPos + str.length);
}); 

$('#nospace').bind('keydown', function(event){
    return event.which !== 32;
});

See it in action here: http://jsfiddle.net/t2a0xa5d/

To explain what I've done here: I've defined two functions, getCursorPosition and setCursorPosition , which are used to find where to insert the (modified) pasted text, and to return to the proper cursor position after a paste.

There are a few downsides to this approach. We are basically reinventing the pasting wheel by calling event.preventDefault() , so some functionality is unavailable. For example, type some text into the input box, select it, then paste something. You would expect the selected text to be replaced, but it is not. It should be fairly simple adding that functionality back if it is so desired, however.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM