Restricting user to enter specific values in input field angular 12

Viewed 402

I have a input field

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

Dollar sign is prefilled. How can I restrict user to enter only the pattern '$1,000.00' (US dollars with $ prefix);

So far , I was able to restrict the user from entering values other than $ , . and numbers But, they can enter consecutive commas, dollar symbol and dots.

handleKeyDown(event:any){
    let key = event.keyCode || event.which;
    if((key>=48 && key<=57) || (key===52 || key===190 || key===188 || key===8)){
      return true;
    }else{
      return false;
    }
 }

To restirct that I am using a Regex and regex works fine. But, I am not sure in which event I should use the Regex.test(), because if I use it in keyup() event the character is already populated in the text filed, there is no point in doing event.preventDefault(). If I do it in keydown() event then I can not extract the complete value of the text field before the keydown() event is finished. And I should also accomodate copy and paste in the field.

There is no privision for blur event, I need to check this during the user input only, and avoid it from appearing in the text filed.

Is there anyway to achieve this? Would you suggest an easier way using the reactive form input field?

1 Answers

Like Sebastian Ciocarlan said you can remove the $ from the input and just allow numbers and commas if you don't need to store the $.

But instead of using a <div> you can use matPrefix from angular material (if you use it) to add $ in front of your input (or matSuffix if you want to put it at the end).

You can see an exemple here : https://material.angular.io/components/form-field/overview#prefix--suffix

Related