1

I created sample spring MVC program to display the student name, id and age. I want to restrict entering of numbers in the textfield and string in place for age. Also I want to make the id field mandatory. I am using JSP for the view.

I had searched a lot but cannot find a suitable solution I am expecting your help, Thanks in advance. This is the jsp file

<%@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>

This were the search result i have found

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

if this link works please help me to integrate it with my JSP file.I am beginner in javascript and HTML.

Thanks in advance

Community
  • 1
  • 1
user2083175
  • 133
  • 5
  • 18
  • what solutions did you find? what did you try? take a look to http://static.springsource.org/spring/docs/3.0.x/reference/validation.html – fGo May 29 '13 at 08:08
  • 1
    spring-mvc validation will work only after posting data to server. Are you sure you want this? Maybe validation need to be implemented on html/js side before posting? – vacuum May 29 '13 at 08:18
  • I would alternatively suggest to take a look at HTML5 form validation features such as the `pattern` attribute, where you could restrict user inputs without one single line of JS. – Thomas Junk Apr 26 '14 at 21:34

1 Answers1

0

For non-numerical fields: One possible solution is to use the keyup function to replace all number occurrences in the text field while you type (jQuery used).

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

});

For numerical only fields: You can use something similar as the above but replace the regexpression with:

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

For id: Use form validation on form submission. First of give an id/name to your form.

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

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

I haven't actually tested the above code completely so any corrections would be appreciated.

Hope it helps

mario
  • 477
  • 3
  • 16