0

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?

1 Answer 1

1

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 email or checkbox) see MDN or this interactive page with demos
  • For more information on cross-browser compatibility of :valid and :invalid, see MDN on :valid and :invalid

Notes

  • These specific input types will also restrict or simplify the input for users. The number inputs will restrict input to numbers only (it will prevent the submission of the form otherwise), and the date inputs 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.
Sign up to request clarification or add additional context in comments.

2 Comments

How to center the <label>?
You could place the whole inputs format inside a table, like this demo. In the CSS code you'll see some code that aligns the labels to the center relative to each other, but you could also apply other styles to them if you want, or disable that code altogether.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.