Excuse me for this simple question. I have aJSP in which I have several forms, each of which consist of multiple text boxes which take different types of text (eg. Date, Name, Balance). How to make the user fill the fields and then only submit to the server? Is it possible to use only one js function?
Add a comment
|
1 Answer
Note: this answer does not use any JSP nor JavaScript, because in HTML5 this is no longer necessary.
You could use HTML5's required attribute on the inputs, and then let the user know the inputs are not correctly filled in via the :invalid CSS pseudo-class. It would look something like this:
HTML:
<form id="myForm" action="#">
<label>Date: <input type="date" name="date" required></label>
<br>
<label>Name: <input type="text" name="firstname" required></label>
<input type="text" name="lastname" required>
<br>
<label>Balance: <input type="number" name="balance" required></label>
<br>
<button>Submit</button>
</form>
CSS:
#myForm input:valid {
background:#AFA;
}
#myForm input:invalid {
background:#FAA;
}
Demo.
Extra info
- For a complete list of input types (such as those listed above, but also ones like
emailorcheckbox) see MDN or this interactive page with demos - For more information on cross-browser compatibility of
:validand:invalid, see MDN on:validand:invalid
Notes
- These specific input types will also restrict or simplify the input for users. The
numberinputs will restrict input to numbers only (it will prevent the submission of the form otherwise), and thedateinputs will clarify to the user how the date should be entered. Both will also simplify entering information to these inputs - Note that not all of these are supported by older browsers, which will often default to the plain text input. See caniuse and MDN's list for the full details on browser support.
- Never rely on client-side verification only. It's very easy to modify forms on the client's side, which could lead to XSS vulnurabilities. Always verify proper input on the server too.