1

I am trying to make an input text that only write \[A-Za-z0-9 -]\ so i put the condition in onkeydown function. It works well. Almost. If you write ẃéŕýúíó (something with accent mark) it doesn't work.

Extreme case:

<input type="text" onkeydown="return false;"/>

I can write á. How to prevent it?

Edit:

Code with \[A-Za-z0-9 -]\

const verif = (event) => {
  const char = event.key
  if(char!=="Unidentified"){// when á return Unidentified
    return /[A-Za-z0-9 -]/.test(char)
  }else{
    console.log("why!!")
    return false
  }
}
//tested on chrome 72
<input type="text" onkeydown="return verif(event);" />
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
ivesklein
  • 34
  • 4

1 Answers1

1

You can use the input event to get changes when the user is typing inside of the field.

$('#test').on('input',(e)=>{
 let newValue = e.currentTarget.value.replace(/[^a-zA-Z0-9 -]/g, '')
  e.currentTarget.value = newValue
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="test" type="text" placeholder="test"/>