Reputation: 125
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
Reputation: 10975
To achieve the expected result, use below options of keyup
event
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