sina
sina

Reputation: 145

how prevent user typing special character in android browsers on keydown event (event.preventDefault not wotking)

the event.preventDefault does not working in android as I know. so what is the best alternative way to prevent user typing special character in android on keydown event. note: the replace value solution when input event fired is good but in my situation doesn't solve the problem.

Upvotes: 5

Views: 380

Answers (1)

Dmitry
Dmitry

Reputation: 99

In my case, the problem with replacing value on input event on Android, was with caret, that jumped to wrong position while typing.

I’ve solved it like this:

let input = document.getElementById("input")

function withoutForbiddenChars(str) {
    // change to your set of chars
    return str.replace(/[^\d]+/g, '')
}

function handleInput(event) {
    let charsBeforeCaret = input.value.slice(0, input.selectionStart)
    let charsAfterCaret = input.value.slice(input.selectionStart)
 
    charsBeforeCaret = withoutForbiddenChars(charsBeforeCaret)
    charsAfterCaret = withoutForbiddenChars(charsAfterCaret)
    
    input.value = charsBeforeCaret + charsAfterCaret
    
    let newCaretPos = charsBeforeCaret.length

    input.selectionStart = newCaretPos
    input.selectionEnd = newCaretPos
}

input.addEventListener('input', handleInput, false)

Demo: https://codepen.io/udovichenko/pen/vYWWjmR

Upvotes: 0

Related Questions