0

I have a text box. I want to make the textbox accept float value when dataType=3 while keypress event. I am able to achieve this for number, but trying to do the same for float. But not able to achieve this. While inserting float point ('dot') it showing me alert message. Is there any way to do it? While i

This is i tried

 <input class="form-control"
               type="text"
               [(ngModel)]="fieldValue"
               (ngModelChange)="onInputTextChange()"
               (keypress)="checkInputType($event)" /> 


checkInputType(event): boolean {
    if (this.dataType === 2) {
      const charCode = event.which ? event.which : event.keyCode;
      if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        this.alertService.error("Can't enter any character");
        return false;
      }
    }

    if (this.dataType === 3) {
      console.log('e')
      //const charCode = event.which ? event.which : event.keyCode;
     if ((event.which != 46) && (event.which < 48 || event.which > 57) || (event.which == 46)) {
      this.alertService.error("Can't enter any character");
      return false;
     }
    }
    return true;
  }
  • Ι would suggest you to use a for-matter for that or implement yours, But it is a tricky concept. I like this one:https://www.npmjs.com/package/ng2-currency-mask – StPaulis Dec 21 '20 at 08:32
  • @StPaulis I didn't understand –  Dec 21 '20 at 08:34
  • Can you create a [stackblitz](https://stackblitz.com/stackblitz) example ? – Alexis Dec 21 '20 at 08:46
  • You can take a look this SO:https://stackoverflow.com/questions/54460923/angular-2-restrict-input-field/54462816#54462816 using a directive – Eliseo Dec 21 '20 at 11:11

1 Answers1

0

For input checking, a simple regex test will work. But a valid floating point number requires you first enter a few characters before its a "valid"

I am assuming by valid float, you mean the number must have a digit followed by a decimal separator followed by decimal values

example

"20.1" -> Valid - will not be a valid "float" until the entire string is entered
"0" -> not valid
".1" -> not valid

Here is regex for the above, which can be modified to suit your needs if my assumptions are incorrect.

/[+-]?([0-9]{1,}[.])[0-9]+/g

https://regexr.com/5iv1v

This type of checking is also best done with the onChange event.

  validateInputOnChange = (e) => {
    //you can get the last key pressed here
    const keyPressValue = e.target.value.slice(-1);

    //your other datatypes

    if (this.dataType === 3) {
      //regex test for floating point numbers. see https://regexr.com/5iv1v
      const regex = /[+-]?([0-9]{1,}[.])[0-9]+/;
      const validFloating = regex.test(e.target.value);
      if (!validFloating) {
        this.alertService.error("Can't enter any character");
        return false;
      }
    }
    return true;
  };

Here is a codesandbox with a simple regex test

GBourke
  • 1,834
  • 1
  • 7
  • 14