Allow user to input numbers only no special character or alphabet in Angular text box

Discussão em 'Angular' iniciado por Paras Panchal, Fevereiro 19, 2025.

  1. I have an input field where the requirement is that it has 0 initially set. On change of value that 0 is removed and a number is added, but that 0 is removed only if the key pressed by the user is a number.

    Now the issue arises that when I do use an input event it takes my value as sing quoted string as '8'. I had used the replace method, but if I press backspace also on focus out it adds a .00 to a number if its there.

    I also found a issue when my number is initially 0 and I press a non-numeric value, it makes my number set to ''. Also on backspace keypress it should allow backspace and remove 0. It should not give an error when I remove the last non-0 number after typing something and do a backspace, but it gives an error Cannot read properties of null (reading 'replace'). That is also a case, so its a mix of various cases.

    <input type="text" class="someclass" [readOnly]="isView || isEdit" placeholder=""
    formControlName="somename" mask="separator.2" thousandSeparator=","
    (input)="removeZeroOnKeydown($event)" (focusout)="onFixedAmount('somename')"
    separatorLimit="99999999999999">
    <label class="label">Some Label$</label>


    removeZeroOnKeydown(event: InputEvent) {
    let inputElement = event.target as HTMLInputElement;

    //Get FormControl Name on keydown
    let controlName = inputElement.getAttribute('formControlName');

    if (!controlName) return;

    let control = this.myformname.controls[controlName];

    //Check Formcontrol input field value
    let controlValue = control.value;

    // If the input field only contains "0", replace it with the input data
    if (controlValue == 0 || controlValue == '') {

    //Get the keypressed value
    let inputData = (event as InputEvent).data;

    //let numberValue = inputData.replace(/'/g, "");

    if (inputData && /^\d$/.test(inputData.replace(/'/g, ""))) {

    //Set value of keypressed
    control.setValue(inputData);
    }
    else {
    if(controlValue == 0 && controlValue){
    control.setValue(0);
    }
    else if(!/^\d$/.test(inputData.replace(/'/g, "")) && controlValue != 0) {
    control.setValue('');
    }
    }
    }

    onFixedAmount(FormControlName) {
    let amount = this.myformname.controls[FormControlName].value;
    if (amount) {
    this.myformname.controls[FormControlName].setValue(amount ? Number(amount).toFixed(2) : 0);
    }
    }

    Continue reading...

Compartilhe esta Página