1

フィールドに数字のみを入力するように制限する必要があります。 私は解決策がありますが、入力フィールドでバックスペースが機能していません。 誰にでも適切な解決策がありますか?入力テキストボックスを制限する方法は、数値をAngular2形式で入力するだけですか?

<input (keypress)="keyPress($event)" minlength="8" maxlength="15" required />

form.html form.component.ts

keyPress(event: any) { 
    const pattern = /[0-9\+\-\ ]/; 
    let inputChar = String.fromCharCode(event.charCode); 
    // console.log(inputChar, e.charCode); 
     if (!pattern.test(inputChar)) { 
     // invalid character, prevent input 
      event.preventDefault(); 
     } 
} 

kepressイベントでは、それは数字のみを入力するようにユーザを制限するが、このコードの問題は、バックスペースで、タブキーはありませんこのコードは私の期待どおりではありません...

+0

可能な複製:http://stackoverflow.com/questions/7295843/allow-only-numbers-to-be-typed-in-a-textbox –

+3

[数値(0-9)のみを許可する方法] HTML入力ボックスのjQueryを使用して?](http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery) – Igor

+1

私はjQueryを使用していません。任意のサービスを作成することによってtypescript-angular2に解決策がありますか。 – RohanArihant

答えて

0

私の答えは次のとおりです。 - form.html:

form.component.ts

restrictNumeric = function (e) { 
    var input; 
    if (e.metaKey || e.ctrlKey) { 
     return true; 
    } 
    if (e.which === 32) { 
     return false; 
    } 
    if (e.which === 0) { 
     return true; 
    } 
    if (e.which < 33) { 
     return true; 
    } 
    input = String.fromCharCode(e.which); 
    return !!/[\d\s]/.test(input); 
} 
0

event.charCodeはマップされませんバックスペースキーの数字のいずれか0-9

バックスペース(例:keyCode = 8)をホワイトリストに登録する必要があります。 (私の頭の上から)このような何か:

if(event.keyCode != 8 && !pattern.test(inputChar)) { 
    event.preventDefault(); 
} 
0

あなたに正規表現を使用して次のように達成することができます:

var numbersOnly = document.getElementById("numbersOnly"); 
 
numbersOnly.onkeyup = function myFunction() { 
 
    numbersOnly.value = numbersOnly.value.replace(/[^0-9]/g, ''); 
 
};
<input id="numbersOnly" minlength="8" maxlength="15" required>

0

あなたはこの方法を使用することができますあまりにも

keyPress(event: any) { 

     const pattern = /[0-9\+\-\ ]/; 
     let inputChar = String.fromCharCode(event.charCode); 

      if (!pattern.test(inputChar) && event.charCode != '0') { 
       event.preventDefault(); 
      } 
    } 
0

MDNを非推奨もはや、それがマークされているに、String.fromCharCode(event.keyCode)を使用し、それが右に動作していないように思わないでくださいクローム&のFirefox上でテストのFirefox 58 A簡単な関数、:

onKeypress(event: any) { 
    const keyChar = event.key; 

    let allowCharacter: boolean; 
    if (keyChar === "-" && event.target.selectionStart !== 0) { 
    allowCharacter = false; 
    } 
    else if (
    keyChar === "Tab" || 
    keyChar === "Enter" || 
    keyChar === "Backspace" || 
    keyChar === "ArrowLeft" || 
    keyChar === "ArrowRight" || 
    keyChar === "Delete") { 
    allowCharacter = true; 
    } 
    else { 
    allowCharacter = (keyChar >= '0' && keyChar <= '9'); 
    } 

    if (!allowCharacter) { 
    event.preventDefault(); 
    } 
} 

私もこのコードに満足していないよとこのためにAngularでより良い図書館が存在することを願っています。

関連する問題