Reputation: 97
I have to create input field in Angular, that input field allow only number with 2 decimal places like '123455.12'
Below is what i have tried so far
<input myCustomDirective type="text">
I created Directive. In my CustomDirective I used HostListener for keypress event in that listener i used regular expression to validate but it allow only number it not allowing to enter '.(dot)'
new RegExp('^[0-9]*$');
// my regular expression
Upvotes: 1
Views: 216
Reputation: 629
Here's a Directive that takes Only Decimal Values with custom precisions.
https://stackblitz.com/edit/angular-decimal-directive
Example:
`<input type="text" [(ngModel)]="myVar" decimal>`
But you can define the precision size like that :-
`<input type="text" [(ngModel)]="myVar" [decimal]="3">`
If you want to use Only Integer not floating point you can use the Directive Like this:
<input type="text" [(ngModel)]="myVar" [decimal]="0">
If you don't complete enough precision in the input , then it will automatically complete rest of the number precision (also if a .(dot) needed) by onblur event.
You Can't inject string value by two way binding.
N.B: [(ngModel)] is mandatory for using the Directive.
Upvotes: 2
Reputation: 395
Please check out the fiddle jsfiddle.net/gsferreira/Lsv9f0b0 , posted in link ,
ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/"
is the key
From Plain Old Java script fiddle link https://jsfiddle.net/j3cbytws/
Only numbers please and a single dot allowed , nothing else:
<input type="number" name="someid" onkeypress="return isNumberKey(event)" />
<script>
var isDecimalAlredyEcountered = false;
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if(isDecimalAlredyEcountered && charCode === 46)
return false;
if(charCode == 46)
{isDecimalAlredyEcountered =true;
}
if (charCode > 31 && (charCode < 48 || charCode > 57)&& charCode != 46)
return false;
return true;
}
</script>
There can be an issue of backspace char and delete with the above implementation, so you have to reset the state on clear
Upvotes: 0