1

I'm just wondering if it's possible to validate or check that at least one radio button has been selected on a form within a servlet?

Or can this type of validation only occur on the client side with JavaScript etc?

As a workaround, I can check a radio button by default, but ideally I would like no radio button initially selected and display an error message if the user tries to submit the form.

I'm only using Java servlets on the web app so it would be great if anyone has done this before using servlets only.

Thanks in advance.

informatik01
  • 16,038
  • 10
  • 74
  • 104
elgoog
  • 1,031
  • 1
  • 11
  • 20

1 Answers1

3

In your servlet, you will get the value of the selected radio if they are in the same group. If the user has not selected any radio, you will receive null value. Let's see it in action:

<form method="POST" action="HelloWorldServlet">
    <input type="radio" name="sampleRadio" value="val1" />Value 1
    <br />
    <input type="radio" name="sampleRadio" value="val2" />Value 2
    <br />
    <input type="submit" value="Hello Servlet" />
</form>

In the servlet side:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    String radio = request.getParameter("sampleRadio");
    if (radio != null)
        System.out.println("value of selected radio: " + radio);
    else
        System.out.println("no radio button was selected");
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • Thats great Luiggi, thank you. I was very close to your solution and I was actually using that same code to store the values of the radio buttons in a session object for processing later on. So as a follow up to this, do you know the best way to redisplay the page with an error and hence not process the next request (if a radio button had been selected)? – elgoog Apr 01 '12 at 16:12
  • @elgoog that should be another question :), but maybe you need some labels next to your radio buttons that must be shown only if there is an error (a session variable that holds the logic value of the error) and redirect to the same page having the error variable with true value. – Luiggi Mendoza Apr 01 '12 at 16:17
  • Yea that seems a good solution. Thanks again Luiggi, your help is much appreciated! – elgoog Apr 01 '12 at 16:39