So I have this input tag:
<input ... onkeypress="return /^[A-Za-z0-9 -]*$/.test(event.key) id="id_title">
And I want it to accept only numbers, letters and spaces. I wonder how to rewrite it in my js file with jquery in modern js version, because all methods from the Internet with old js are crossed out. Like in here, https://www.codegrepper.com/code-examples/javascript/allow only letters in input javascript onkeypress or keyCode methods are not working now. They are crossed out.
$('#id_title').on('keydown', function() {
let regex = /^[A-Za-z0-9 -]*$/ // accepts only letters, numbers and spaces
... // how to continue?
}
Thanks in advance!
CodePudding user response:
Try this -
$('#id_title').on('input', function(event) {
let regex = /^[A-Za-z0-9 -]*$/;
return regex.test(event.key);
});
Check out the MDN docs on the test
method!