Limit the user input period in the input field on Android

I want to limit the user to enter a special character in the number field on an Android device. "." (period) does not skip values โ€‹โ€‹in the onkeypress event as expected.

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

But with <input type="number"/>I can not limit the user to enter a keyword.

Tried a lot of stack overflow messages. But still no luck.

Below is the code I'm 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 use the event keydownbecause the event keypressdoes not fire when I press the dot key on the numeric keypad.

, e.key Unidentified, . .

, , .

.

Android Nexus 5X.

+4
3

, , , $timeout, , , - .

type="tel" ( , , type="number") on-change:

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

angular $timeout onChange():

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);
     }
}

, RegExp, - , Android NumberPad .

, -!

+1

Edit: , , JavaScript .

<div>
<input onkeypress='return event.charCode >= 48 && event.charCode <= 57' type="number" placeholder="Input Value" />
</div>

jsfiddle http://jsfiddle.net/tZPg4/16784/

0

, , jQuery setTimeout:

<input type="number" name="test" inputmode="numeric" pattern="[0-9]*" step="1" class="only-numbers" />


$(document).on('keydown', '.only-numbers', function (e) {
    var inputElement = $(this);
    if (e.which < 48 || e.which > 57) {
        window.setTimeout(function () {
            inputElement.attr('type', 'text').attr('type', 'number');
        }, 100);
    }
});

setTimeout, .

, -, โ€‹โ€‹ .

0
source

Source: https://habr.com/ru/post/1661583/


All Articles