How to allow only numbers and semicolons in input text?

Asked

Viewed 30 times

0

I have an input in my system where the user must enter code (only numbers), however he can put several codes, and to separate uses semicolon (;).

To make it work I created the input as text and put a function, which is called via Event (input), which performs the following action:

Input:

<input [disabled]="!selectHierarchy" id="numero" name="pesquisa" type="text" (input)="validaNumber()">

Function:

validaNumber(){
  let input = <HTMLInputElement>document.querySelector("#numero");
  input.value = input.value.replace(/[^0-9\;]/, '');
}

It worked, when I type it only appears number and semicolon.

But if I copy a text, and paste it into the input, normal text appears. How to make this validation work also when the user pastes a text?

  • Already tried to use the event ngChange? because the validation will only occur when there are changes in the input value

1 answer

0


I managed to solve!

I added Event Binding (Paste) which calls a function when someone tries to paste some text:

<input [disabled]="!selectHierarchy" id="numero" name="pesquisa" type="text" (input)="validaNumber()" (paste)="teste($event)">

In the function I created a regex with everything that should not be accepted in the input, take the value and check if there is any match using regex.test():

teste(event: ClipboardEvent){
let reg = /[a-zA-Z!@#$%^&*()_+\-=\[\]{}':"\\|,.<>\/?]/i;
let clipboardData = event.clipboardData;
let pastedText = clipboardData.getData('text');

 if (reg.test(pastedText)){
   event.preventDefault();
   event.cancelBubble = true;
   return false;
 }
}

If you do, cancel the event and don’t let it paste text.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.