0

以下是添加新基金的代码,其中 min_holdings 和 nav 是 int 值,而所有其他都是 varchar 和 text 字段。在输入这些字段时,我想确保用户输入正确的格式,例如 int 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/名称来指定您期望的输入类型。
只是为了向您展示我检查输入的方式:

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,这将等同于假,如果输入是数字,这将是真。如果没有输入,则比较等于:

'' == 0

也就是说,这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 回答
0

您可以使用 JQuery Validation 插件。这将有所帮助:

http://jqueryvalidation.org/

于 2013-06-10T10:40:04.497 回答