1

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!

1

1 Answer 1

3

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!

Sign up to request clarification or add additional context in comments.

5 Comments

Hmm, okay, will it prevent the user for inputting for example "="?
Umm actually, it doesn't preserver the user from inputting it :/
change input to keydown or keypress, that's what onkeypress is
Yarin_007, yeah thanks, but why input doesn't work here?
event.key is undefined. Instead of .on('input'), you need .on('keypress'). But even that won't prevent a user from pasting an invalid character. For better answers to OP, see How do I block or restrict special characters from input fields with jquery?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.