Vyshnavi
Vyshnavi

Reputation: 125

How to stop the characters in Input type="text" field in angular

My client requirement is as follows 1. The input field should be a text 2. It should not allow characters 3. It should have range of 0-100 4. Input format is 99.99

we are using angular 7. Pattern is not working for the validation

Can someone please help me. I am struggling from one day :( Thanks!

Upvotes: 0

Views: 1761

Answers (1)

Naga Sai A
Naga Sai A

Reputation: 10975

To achieve the expected result, use below options of keyup event

  1. On every key up, slit input value by '.'
  2. The first part of the split array will have value before the decimal point and the second part of the array will have value after decimal point
  3. Reassign input value based on length

component.html

<input type="text" (keyup)="onKeyup($event)" />

component.ts

 onKeyup(e) {
    const val = e.target.value.split(".");
    if (!val[1]) {
      e.target.value =
        val[0].split("").length > 2
          ? e.target.value.substr(0, e.target.value.length - 1)
          : e.target.value;
    } else {
      e.target.value =
        val[1].split("").length > 2
          ? val[0] + "." + val[1].substr(0, val[1].length - 1)
          : e.target.value;
    }
  }

working code sample for reference - https://codesandbox.io/s/angular-p1gh1

Updated code with HTML and javascript

codepen - https://codepen.io/nagasai/pen/xoLqdN?editors=1010

function onKeyup(e) {
  const val = e.target.value.split(".");
    if (!val[1]) {
      e.target.value =
        val[0].split("").length > 2
          ? e.target.value.substr(0, e.target.value.length - 1)
          : e.target.value;
    } else {
      e.target.value =
        val[1].split("").length > 2
          ? val[0] + "." + val[1].substr(0, val[1].length - 1)
          : e.target.value;
    }
  }
<input type="text" onkeyup ="onKeyup(event)"/>

Upvotes: 1

Related Questions