-1

ユーザーが最初の数字として 0 を入力できないようにしようとしています。

これは私が持っているコードです

function validate_numberonly(evt)
{
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode( key );
    var regex = /[0-9]|\./;
    if( !regex.test(key) ) {
        theEvent.returnValue = false;
        theEvent.preventDefault();
    } 
}

これを許可する正規表現は次replace(/[^0-9]/g,'');のとおりですが、現在の正規表現の代わりにこれを入力してもうまくいかないようです

4

4 に答える 4

0

keypress ascii 値を読み取ってテストしましたか?

次のようなことを言ってください。

//when key is pressed in the textbox$("#quantity").keypress(function (e)
{
  //if the letter is not digit then display error and don't type anything
   if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))
   {
    //display error message
    $("#errmsg").html("Digits Only").show().fadeOut("slow");
    return false;

} });

上記の例を調整して '0' ASCII 文字コードを検出すると、正規表現を使用する方が簡単になる場合があります。現在のテキスト ボックスの文字列の長さをテストし、1 より大きい場合は関数を終了できます。

コードサンプル: http://roshanbh.com.np/2008/04/textbox-accept-only-numbers-digits.html

于 2013-11-12T20:06:03.220 に答える
0

記録のために、これはうまくいきました

<input type="text" onblur="this.value=this.value.replace(/^0+/, '')">
于 2013-11-13T09:00:06.750 に答える