0

I am trying to restrict alphabets in javascript. Here is the code I am using and I am able to show alert to users "Enter numbers only" if they enter alphabets.

But issue is after entering values in the textbox, if I try to backspace the values, it shows alert("Enter numbers only"

How to not show alert if I press backspace key.

Here is my code,

       PasswordCheck(event)  
        {
              var allowedRegex =  /^[0-9]+$/ && event.keyCode === 8;     
              if (!event.key.match(allowedRegex)) {
              alert("Enter Numbers only")
              event.preventDefault();
        }

       
         <form (keyup)="PasscodeCheck($event)" autocomplete="off">
         ......
         </form>
2
  • Isn't keyCode deprecated? Commented Nov 16, 2020 at 13:38
  • 1
    Can't you just use an input box with type text? Commented Nov 16, 2020 at 14:02

1 Answer 1

1
 PasswordCheck(event) {
    var allowedRegex =  /^[0-9]+$/;     
    if (!event.key.match(allowedRegex) && event.keyCode !== 8) {
      alert("Enter Numbers only");
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

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.