sveltesvelte-3sveltekit

Disable spaces in input field on svelte


I am trying to disable spaces in the Username text field

As Disable spaces in Input, AND allow back arrow?, this should be like this:

<input on:keydown={(e) => e.which !== 32} />

But I still able to input space


Solution

  • Here's a solution where spaces are prevented of being typed and removed from pasted text REPL

    <script>
        let value
        
        function handleKeydown(event) {
            // prevent that a space is typed
            if(event.code === 'Space') event.preventDefault()
        }
        
        function handleInput(event) {
            // remove spaces from pasted text
            value = value.replaceAll(' ', '')       
        }   
    </script>
    
    <input type="text"
                 bind:value
                 on:keydown={handleKeydown}
                 on:input={handleInput}>