Reputation: 624
I was wondering if you guys can help me out on building a function in Javascript that is executed in the keypress event that prevents to have more than 10 digits as Integer and 2 as decimals.
Correct format: 1234567890.12 (10 digits as integer and 2 decimal)
Wrong format: 123456778901.123 (11 digits as integer and 3 decimal)
In case the user enters more than 10 digits as integer, it should return false to not add it but to leave the 2 decimal points if defined already.
I would do it myself but I ran out of ideas :(
This is what I was trying but it never let me to respect the 2 decimal points.
const theIntegerNumber = ($scope[ngModelName] - ($scope[ngModelName] % 1).toFixed(2)).toFixed(0);
if( theIntegerNumber.length >= 10){
$scope[ngModelName] = parseFloat($scope[ngModelName]).toFixed(2);
$event.preventDefault();
}
// I am using angular tho.
Edit:
<input ng-model="__incomeUnitAmount" ng-keypress="filterValueAcceptedData('__incomeUnitAmount', '__incomeUnitAmount_error_format', '10Digit2Decimal', $event);" type="text" name="incomeUnitAmount-amount"
>
Upvotes: 0
Views: 47
Reputation: 15461
Using regular expressions:
var regex = new RegExp("^\\d{0,10}\.\\d{2}$");
isValidFormat = function(str) {
return regex.test(str);
}
console.log('%s: %s', '1234567890.10', isValidFormat("1234567890.10"));
console.log('%s: %s', '123456778901.123', isValidFormat("123456778901.123"));
Edit:
The pattern has been updated to make the dot and the fractional part of number optionals (because dot and decimals are generally not immediately entered by the user).
With Angular, using the ng-pattern
directive:
function formCtrl($scope){
$scope.onSubmit = function(){
alert("form submitted");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<form name="myForm">
<input type="text" ng-model="intValue" name="int_field" ng-pattern="/^\d{1,10}\.?\d{0,2}$/" required><br/>
<span ng-show="myForm.int_field.$error.pattern">Not a valid number!</span><br/>
<tt>myForm.price_field.$error.pattern = {{myForm.int_field.$error.pattern}}</tt><br/>
</form>
</div>
Upvotes: 1