skip to Main Content

I’m looking for a way to prevent a user entering negative numbers , but allow them to type floating numbers

  • I’m using angular so angular tools also is a consideration
    Thanks !

2

Answers


  1. I did a directive recently for exactly that purpose. Consider improvements over it.

    @Directive({
        selector: '[money]',
        standalone: true
    })
    export class MoneyDirective {
        moneyRegex = /^[0-9]+$|^[0-9]+.$|^[0-9]+(.[0-9])$|^[0-9]+(.[0-9][0-9])$/;
    
        constructor(private ngControl: NgControl) {}
    
        @HostListener('change', ['$event'])
        onChange(event: Event): void {
            if(this.ngControl.control?.valid && this.ngControl.control instanceof FormControl) {
                let value: number = +this.ngControl.value;
                this.ngControl.control.setValue(value.toFixed(2));
            }
        }
    
        @HostListener('input', ['$event'])
        onInput(event: InputEvent): void {
            if (!this.moneyRegex.test(this.ngControl.control?.value)) {
                let control = this.ngControl.control as FormControl;
                control.setValue(control?.value?.substring(0, control?.value?.length -1));
            }
        }
    }
    

    Then just

     <input formControlName="price" money>
    
    Login or Signup to reply.
  2. You can use a simple javascript function on keypress and detect when the user enters a - and disable that. event.charCode != 45 detects and disables the user from typing a dash (-).

    <input type="text" onkeypress="return event.charCode != 45">

    An alternative to prevent user from enter any type of text and just enable only number you can change the type of the input field to number and add also the min attribute as 0. You can also add step attribute to be decimal.

    <input type="number" min=0.01 step=0.01 onkeypress="return event.charCode != 45">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search