Kumail Hussain
Kumail Hussain

Reputation: 879

Keyup prevent default not working angular6

I want to stop entering any number after validating a custom regular expression , the issue is condition got true but event.preventDefault is not preventing the input , The reg ex is to input value in percentage between 1-100 with decimals

/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/

this is my input

<input  type='text' (keyup)="preventPercentage($event)"  [(ngModel)]="value">

ts

preventPercentage(event){
  var p = event.target.value
  var s= p.match(/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/)  != null
  if(!s && p){
    event.preventDefault();
  }
}

user can still enter any value even the condition is true input anything between 100 above it still working and event is not preventing values

  <input  type='text' (keydown)="preventPercentage($event)"  [(ngModel)]="value">

I used key down but it allows to enter 123 i.e three digit numbers and I cannot then remove that number using backspace what exactly I am doing wrong can anyone suggest a sol any help will be appreciated

Upvotes: 2

Views: 5462

Answers (3)

A. Morel
A. Morel

Reputation: 10344

This is because it's necessary to use keydown event, not keyup.

It considers that the keyboard action is already done and you cannot cancel it.

Upvotes: 0

Lovlesh
Lovlesh

Reputation: 832

preventPercentage(event: any) {
      function stopProgram() {
        event.stopPropagation();
        return false;
      }
      if (event.keyCode === 8) {
        return true;
      }
      var p = event.target.value;
      if ((event.keyCode === 190 && p.indexOf('.') > -1) || p === '100') {
        return stopProgram();
      }
      p = p + event.key;
      var s = p.match(/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/) != null;
      if (!s && event.keyCode !== 190) {
        return stopProgram();
      }
    }

Upvotes: 1

Lovlesh
Lovlesh

Reputation: 832

Try this. I think there is a change required in the regex as per your requirement.

preventPercentage(event){
  var p = event.target.value + event.key;
  var s = p.match(/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/) != null;
  if (!s && event.keyCode !== 8) {
    event.stopPropagation();
    return false;
  }
}

Use this with keydown:

<input  type='text' (keydown)="preventPercentage($event)" [(ngModel)]="value">

Upvotes: 1

Related Questions