[英]Restrict the user entering period in input field on Android
我想限制用戶在Android設備的數字字段中輸入特殊字符。 “。” (點)字符未按預期在“onkeypress”事件中傳遞值。
使用<input type="text">
我可以阻止用戶輸入任何特殊字符。
但是使用<input type="number"/>
我無法限制用戶輸入點密鑰。
試過很多堆棧溢出帖子。 但仍然沒有運氣。
以下是我正在嘗試的代碼:
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;
}
});
}
}
}])
我正在使用keydown
事件,因為keypress
數字鍵盤上的點鍵不會觸發keypress
事件。
此外,當用戶輸入點密鑰時,我收到的電子e.key
為Unidentified
。 所以我試圖用它來操縱。
我已嘗試在用戶輸入點密鑰時修剪最后一個值,但也無效。
請建議任何可能的方式。
在Android Nexus 5X
設備中嘗試了上述代碼。
嗯,我知道這是一個糟糕的解決方案,因為它使用$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狀態的字符。
希望它可以幫到某人!
編輯:我沒有正確理解問題,這個解決方案不適用於移動設備,這是輸入字段的簡單javascript解決方案。
<div>
<input onkeypress='return event.charCode >= 48 && event.charCode <= 57' type="number" placeholder="Input Value" />
</div>
這是工作jsfiddle http://jsfiddle.net/tZPg4/16784/
這是使用輸入數字,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延遲。
我希望它可以幫助那些有同樣煩人問題的人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.