toString().length on a number with zeros and only zeros always returns 0

Viewed 179

I'm working on a page that accepts 4 digits (exactly 4 digits) pin from users. Something like this.

<input type="number" ng-model="passCode" class="form-control" onpaste="return false" id="passCodeField"  ng-disabled="!enablePassCode" ng-change="onInputPasscode()" ng-keypress="onKeyPressPasscode($event)"/>

onKeyPressPasscode function

$scope.onKeyPressPasscode = function($event) {
    if(isNaN(String.fromCharCode($event.which || $event.keyCode))){
        $event.preventDefault();
     }
}

onInputPasscode() function :

$scope.onInputPasscode = function() {
    if ($scope.passCode.toString().length > 4){
        $scope.passCode = $scope.passcode;
    }
    if($scope.passCode.toString().length == 4) {
         $scope.passcode = $scope.passCode;
         $scope.disableContinue = false;
         session.put('pinFlow',true);
    } else {
         console.log("current length - " + $scope.passCode);
         $scope.disableContinue = true;
         session.put('pinFlow',false);
    }

}

This is failing when the input is all zeros. i.e current length is not getting updated hence the user is allowed input as many zeros as he wants. How do I take 4 digit zeros as input and still meet the checks that I have?

debugging image

This is in angular 1.5.8v. And I'm not an expert in AngularJS. So any help would be appreciated. Also, please let me know if need any other info. I'll update the answer accordingly.

Thanks in advance.

2 Answers

It's not possible to do this with a an input with type set to number. When user enters a number 0001, that's actually 1. Things like PINs should be handled with type set to text. You can then use a regex for validation.

To allow exactly four digits, no more and no less, use the following regex:

^\d{4,4}$

From JavaScript, use this regex to test a string, like the following:

/^\d{4,4}$/.test('1234')
// => true

/^\d{4,4}$/.test('123456')
// => false

/^\d{4,4}$/.test('12')
// => false

The cause of your problem is that if you PIN Scheme allows for leadings zeros, number is not the ideal type for this (because in numbers, leading zeros can be omitted without changing meaning).

Instead, use input type=text or probably even better, input type=password. Also, I wouldn't listen to keypress - instead use the input event.

Related