Create a Valid Number #Angular directive that handles decimal points

angular-webapi-valid-number

The below ‘validNumber’ directive verifies that the input field has a valid number by checking the last key pressed. If it is a valid number it continues the operation, but if not the directive prevents the input action and the character is not inserted in the input box.

 

This directive also handles decimal points. To enable this option, you have to add ‘enable-decimals’ as an attribute in the <input type=”text”> html code and assign ‘true’ or ‘false’ as required.

module.directive("validNumber", function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            if (!ngModelCtrl) {
                return;
            }
  
            element.bind('keypress', function (event) {
                /// handle one decimal point only
                if (event.keyCode == 46 && attrs.enableDecimals == "true") {
                    if (this.value && this.value.split('.').length > 1) {
                        event.preventDefault();
                    }
                }
                /// allow only numbers to be entered
                else if (event.keyCode > 31 && (event.keyCode < 48 || event.keyCode > 57)) {
                    event.preventDefault();
                }
            });
        }
    };
});

 

Below are some examples on how to use this directive in html, the first code to disable decimal places and the second code to allow them:

<input type="number" ng-model="idnumber" name="idnumber"
       maxlength="9" min="1" max="999999999"
       valid-number
       enable-decimals="false"
       required />
 
<input type="number" ng-model="depositAmount" name="depositAmount"
       min="5" max="999999999"
       valid-number
       enable-decimals="true"
       required />

 

Happy Validating 🙂

Hello, nice to meet you

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Leave a Reply