0

In Angular 7, how can I mask an input field (textbox) such that it accepts only decimal value like (8.15 or 15.25) ?

I have the following HTML input:

<input type="text" name="amount" id="amount" pattern="[0-9]+(\.[0-9][0-9]?)?" (keypress)="numbersOnly($event)">

i have following function numbersOnly which allow only decimal numbers but it should not allow to enter decimal point(.) more than one time like below.

8.155454 or 8.65.24

it should allow only 1 decimal points after number like below.

8.15 or 80.45 or 555.14

below is my function that accept only decimal value.

 numbersOnly(event: any) {
    let charCode = (event.which) ? event.which : event.keyCode;
    if (charCode != 46 && charCode > 31
        && (charCode < 48 || charCode > 57))
        return false;
    return true;
  }
sunil
  • 195
  • 1
  • 3
  • 11
  • 1
    You should leverage HTML5's `` https://stackoverflow.com/q/19011861/2191572 – MonkeyZeus Feb 27 '20 at 14:28
  • @MonkeyZeus sorry but it also allow to enter decimal point (.) more than one time, i want to restrict it at the time of input it should allow only one decimal point (.) – sunil Feb 27 '20 at 14:29

1 Answers1

0

You can use the keypress event to capture the input values and check in the event handler that there is only one decimal point.

I've done this by adding onkeypress="return slideNumber_keyFilter( event );" to my input element and then used this function:

      <script>
        function slideNumber_keyFilter( event ) {
          return ( ( event.charCode >= 48 ) && ( event.charCode <= 57 ) );
        }
      </script>

Which in my case didn't allow for any periods, but you can simply replace the code that check the input and keep track if a period is entered, and disallow another.