0

以下は、min_holdings と nav が int 値で、他はすべて varchar とテキスト フィールドである新しいファンドを追加するためのコードです。これらのフィールドを入力している間、int のような正しい形式がユーザーによって入力されていることを確認したい char やint の文字列..もしそうなら、アラート ボックスが来るはずです..それを行う方法???!!!

 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 <title>Insert title here</title>
 </head>
 <body>
 <form method="post" action="AddMF">
 <center>
 <table>
 <tr>    
 <td>Fund Code</td><td><input type="text" name="mf_code"></td>
 </tr>
 <tr>
 <td>Name</td><td><input type="text" name="mf_name"></td>
 </tr>
 <tr>
 <td>Fund Type</td><td><input type="text" name="mf_type"></td>
 </tr>
 <tr>
 <td>Current NAV</td><td><input type="text" name="nav"></td>
 </tr>
 <tr>
 <td>Minimum Holdings</td><td><input type="text" name="mf_min_holdings"></td>
 </tr>
 <tr>
 <td>Description</td><td><input type="text" name="mf_description"></td>
 </tr>
 <tr>
 <td>Termd and Conditions</td><td> <input type="text" name="mf_TandC"></td>
 </tr>

 </table>

 <br>
 <input type="submit" value="submit">
 </center>
 </form>


 </body>
 </html>
4

2 に答える 2

0

フォームに id を付けて、次のように言いますfrmId

<form id='frmId' method='post' action='AddMF'>

次に、次の JS を追加します。

//assuming window.onload or something
document.getElementById('frmId').onsubmit = function(e)
{
    e = e || window.event;
    var inputs = this.elements,
    i, val;
    for (i=0;i<inputs.length;i++)
    {
        if (inputs[i].value.trim() == +(inputs[i].value.trim()) && inputs[i].value.trim().length > 0)
        {//trim value, continue
            inputs[i].value = inputs[i].value.trim();
            continue;
        }
        alert('Expected numeric input, saw: "' + inputs[i].value +'"');
        //stop submitting the form
        if (e.preventDefault)
        {
            e.preventDefault();
            e.stopPropagation();
        }
        e.returnValue = false;
        e.cancelBubble = true;
        return false;
    }
};

ここで、上記のコードは、すべての入力が数値であることを前提としています。クラスまたはさまざまな入力要素の id/name を使用して、期待する入力のタイプを指定できます。
入力をチェックする方法を示すために:

inputs[i].value.trim()//strip all trailing and leading spaces from input
  == +(inputs[i].value.trim())//loose comparison to the same value, coerced to a number

これは次のようになります。

'1' == 1 or 'a' == 0

ユーザーが を入力した場合a、これは false と同等になり、入力が数値の場合は true になります。入力がない場合、比較は次のようになります。

'' == 0

これが、入力値が少なくとも1 文字の長さであることを確認するために、 true: を追加した理由です。&& inputs[i].value.trim().length > 0

英数字入力を確認したい場合は、次のような正規表現を使用できます。

inputs[i].value.test(/^[a-z]+$/i)//only chars from a to z, case insensitive

などなど...しかし、正規表現を説明することは、ここで簡単にできることではありません。「regex javascript」をグーグルで検索して、それらを愛することを学びましょう...そして、それらを憎むことも大好きです:)

于 2013-06-10T10:58:30.520 に答える