Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict the user entering period in input field on Android

I want to restrict the user from entering special character in a number field on an Android device. The "." (dot) character is not passing values in an "onkeypress" event, as expected.

With <input type="text"> I can able to block the user from entering any special character.

But with <input type="number"/> I am not able to restrict the user from entering dot key.

Tried with many stack overflow posts. But still no luck.

Below is the code i am trying:

HTML

<input type="number" ng-model="registrationField.mobilenumber" tabindex="0" no-special-character="^[0-9-]*$" >

JS

app.directive("noSpecialCharacter", [function() {
    return {
        restrict: "A",
        link: function(scope, elem, attrs) {
            var limit = parseInt(attrs.limitTo);
            var regex = RegExp(attrs.noSpecialCharacter);
            angular.element(elem).on("keydown", function(e) {
                if(e.key == "Unidentified"){
                    e.preventDefault();
                    return false;
                }
            });
        }
    }
}])

I am using keydown event because keypress event is not triggering on press of dot key in number keypad.

Also, I am receiving the e.key as Unidentified when user has entered the dot key. So i am trying to manipulate with it.

I have tried with trimming the last value when the user has entered the dot key and that is also not working.

Please suggest any possible way.

Tried the above code in Android Nexus 5X device.

like image 838
sasi Avatar asked Nov 09 '22 05:11

sasi


1 Answers

Well, I know this is a bad solution since it uses the $timeout service but at least anything after fighting this all day long..

First of all set the type to type="tel" (don't know why but the same doesn't work with type="number") register the on-change event:

<input type="tel" ng-model="$ctrl.numberField" ng-change="$ctrl.onChange()" />

Then in your controller inject the angular $timeout service and define the onChange() function:

onChange() {
    // the below code is relevant for Android platform in cordova
    if (typeof cordova != 'undefined' && cordova.platformId == "android") {
        // filter all available input characters in Android NumPad mode
        var r = new RegExp("[#/;,N\(\)\.\*\-]");
        if (r.test(this.data)) {
            // perform the filter after the digest cycle of angular is complete
            this.$timeout(() => {
                this.data = this.data.replace(r, "");
          }, 100);
     }
}

All the weird characters you see in the RegExp object are those that Android can place in the NumberPad state of its keyboard.

Hope it helps someone!

like image 79
Lentyai Avatar answered Nov 14 '22 21:11

Lentyai