2013-05-29 38 views
1

我創建了示例Spring MVC程序來顯示學生姓名,ID和年齡。我想限制在文本字段中輸入數字,併爲年齡限制字符串。另外我想讓id字段是強制性的。我使用JSP作爲視圖。在文本文件中限制整數

我已經搜索了很多,但找不到合適的解決方案 我期待您的幫助, 在此先感謝。 這是JSP文件

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> 
<html> 
<head> 
<title>Spring MVC Form Handling</title> 
</head> 
<body> 

<h2>Student Information</h2> 

<form:form method="POST" action="addstudent"> 

<table> 
    <tr> 
    <td><form:label path="name" id="tct" >Name</form:label></td> 
    <td><form:input path="name" /></td> 

</tr> 

<tr> 

    <td><form:label path="age">Age</form:label></td> 
    <td><form:input path="age" /></td> 

</tr> 
<tr> 
    <td><form:label path="id">id</form:label> </td> 
    <td><form:input path="id" /></td> 
</tr> 
<tr> 
    <td colspan="2"> 
     <input type="submit" value="Submit"/> 

    </td> 

</tr> 

</table> 

</form:form> 

這是搜索結果我發現

restrict a character to type in a text box

Restricting input to textbox: allowing only numbers and decimal point

http://www.cambiaresearch.com/articles/39/how-can-i-use-javascript-to-allow-only-numbers-to-be-entered-in-a-textbox

如果這個鏈接有效,請幫我把它和我的JSP文件整合起來。我是初學JavaScript和HTML。

預先感謝

+0

你發現了什麼解決方案?你嘗試了什麼?看看http://static.springsource.org/spring/docs/3.0.x/reference/validation.html – fGo

+1

只有在將數據發佈到服務器後,spring-mvc驗證才能正常工作。你確定你想要嗎?也許驗證需要在發佈之前在html/js端執行? – vacuum

+0

我可能會建議看一下HTML5表單驗證功能,例如'pattern'屬性,您可以在其中限制用戶輸入,而不用一行JS。 –

回答

0

對於非數值字段: 一種可能的解決方案是使用所述KEYUP函數來替換所有發生次數在文本字段中鍵入時(jQuery的使用)。

$(".textfield").keyup(function(){ 
    var textfield= $(this).val(); 
    var newtext=textfield.replace(/[0-9]/g, ''); 
    $(this).val(newtext); 

}); 

對於數字僅領域: 可以使用與上述類似,但與更換regexpression:

var newtext=textfield.replace(/[A-Za-z$-]/g, ""); 

對於ID:表單提交 使用表單驗證。首先給你的表單一個ID /名字。

$("form").submit(function(){ 
    var idField= $(#idField).val(); 
    if(idField.length > 0){ //form ok 

    }else{ //form not ok. error message 
     alert('error'); 
    } 
}); 

我還沒有真正測試過上述代碼,所以任何更正將不勝感激。

希望它有幫助