0

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!

5
  • 1
    Why not use type="number"? Commented Jun 26, 2019 at 13:49
  • when I use a number, we get a up and down arrow which is not as part of requirement. Thanks Commented Jun 26, 2019 at 14:35
  • You can try the technique given in this answer to hide the arrows. Commented Jun 26, 2019 at 14:39
  • you can try using mask: npmjs.com/package/ngx-mask Commented Jun 26, 2019 at 16:13
  • you can make your custom validator function this may help stackoverflow.com/questions/39847862/… Commented Jun 26, 2019 at 18:40

1 Answer 1

1

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)"/>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.