Click here to Skip to main content
15,891,473 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
.NET 3.5 using VB

After hours of research and trial-and-error, I find myself still stuck on trying to validate individual radio buttons (NOT radiobuttonlist). At the end of this question, I'll explain why I don't think I can use a radiobuttonlist (which may just be that I don't want to!).

In short, I have a rather large matrix of questions that need answered. Answers are provided by radiobutton option, not dropdown (client demands radiobuttons).

I need to validate that each question has a radiobutton selected at form submission. I want the validation to occur client side.

I created javascript to return the validation, but I continue to run into various roadblocks trying to get the error message to display.

First roadblock was by not using radiobuttonlist, I was having difficulty obtaining the desired radio buttons to validate by group name. I found various examples that seemed like it would have worked, but never did. I ended up with the function I have posted below. Pretty it is not, but it works. Sadly, I will need one of these functions for each row, but at this point, I don't care.

Second roadblock was that the CustomValidator requires some input element as its ControlToValidate. I have no such control since RadioButton is not a valid input element (odd?). So to circumnavigate this problem, I inserted a text box to pass as the control to validate. Obviously I would not want this text box to show, so I set a style to display: none. Well, this didn't work because it seems the CustomValidator inherits the display property of the ControlToValidate (again, odd?); so when the TextBox is hidden, the error message from the validator is also hidden. I have confirmed the validator is fired, and the validator works if the display property is set to something other than none.

Okay, sorry for the long intro, but I know if I don't answer that stuff it will all be asked anyway.

So onto the juicy stuff, here's the code I have to this point.

CSS:
CSS
.DoNotShow
{
    display: none;
}
.Show
{
    display: block;
}


javascript:
JavaScript
function validateEvaluationTableRow1(oSrc, args)
{
   var rbtnValue = null;
   var valueCol1 = document.getElementsByName('<%= rdoEvalSatRow1.ClientID %>')[0].checked;
   var valueCol2 = document.getElementsByName('<%= rdoEvalNeedsImprovRow1.ClientID %>')[0].checked;
   var valueCol3 = document.getElementsByName('<%= rdoEvalUnsatRow1.ClientID %>')[0].checked;
   var valueCol4 = document.getElementsByName('<%= rdoEvalUnableRow1.ClientID %>')[0].checked;
   var valueCol5 = document.getElementsByName('<%= rdoEvalNARow1.ClientID %>')[0].checked;
    
    alert(valueCol1 || valueCol2 || valueCol3 || valueCol4 || valueCol5);
    
    args.IsValid = (valueCol1 || valueCol2 || valueCol3 || valueCol4 || valueCol5);
 }


ASP.NET Code:
VB
<table width="100%" cellpadding="0" cellspacing="0">
    <tr>
        <th>
        </th>
        <th valign="top" align="center">
            Satisfactory
        </th>
        <th valign="top" align="center">
            Needs<br />
            Improvement
        </th>
        <th valign="top" align="center">
            Unsatisfactory
        </th>
        <th valign="top" align="center">
            Unable<br />
            To Evaluate
        </th>
        <th valign="top" align="center">
            N/A
        </th>
    </tr>
    <tr bgcolor="#E1E1EA">
        <td>
            <asp:CustomValidator ID="vldRow1" runat="server" ControlToValidate="TextBox1" Enabled="True"
                Height="18px" ErrorMessage="Selection Required<br>" SetFocusOnError="True" Visible="True" CssClass="Show"
                Display="Dynamic" ValidateEmptyText="true" ClientValidationFunction="validateEvaluationTableRow1" />
            <asp:Label ID="Label1" runat="server" Text="Label">Level of clinical activity</asp:Label>
            <asp:TextBox ID="TextBox1" runat="server" Visible="true" Width="0"  CssClass="DoNotShow" />
        </td>
        <td align="center">
            <asp:RadioButton ID="rdoEvalSatRow1" runat="server" GroupName="Row1" />
        </td>
        <td align="center">
            <asp:RadioButton ID="rdoEvalNeedsImprovRow1" runat="server" GroupName="Row1" />
        </td>
        <td align="center">
            <asp:RadioButton ID="rdoEvalUnsatRow1" runat="server" GroupName="Row1" />
        </td>
        <td align="center">
            <asp:RadioButton ID="rdoEvalUnableRow1" runat="server" GroupName="Row1" />
        </td>
        <td align="center">
            <asp:RadioButton ID="rdoEvalNARow1" runat="server" GroupName="Row1" />
        </td>
    </tr>
    {... lots more rows ...}
</table>


I would love to do away with the silly textbox; I'm okay with the javascript function; I just need the validator to work!

So, can I use radiobuttonlist? Perhaps, but I don't know of a good way to align the header of the matrix with the individual radiobuttons in each column. And this matrix is pretty large and I have several other forms that have a similar matrix, so to redo this matrix in some other fashion is going to take a pretty lot of work too. Sadly, the validation requirement was not part the initial requirements when this form was developed, but the client decided it would be nice to have it.

Thanks for taking the time to read all this. Any help and suggestions would be greatly appreciated! Keep in mind the code you see here is obviously a subset of a larger project and some of it is done just for troubleshooting, so please don't get hung-up on naming or wording.
Posted
Comments
Abdul Quader Mamun 14-Jul-12 22:08pm    
you should describe your question briefly.
jkirkerx 15-Jul-12 0:34am    
That was a big read. Well, poor planning. With a rb list, it's a small amount of javascript to validate. Without, much more code.

1 solution

Well, I'm not going to write your code a be a brogrammer, this is just a hint of how I would do it, but it uses jquery, which is no big deal, can be converted to just plain javascript. It's just a concept to give you an idea. The blur event should work, when leaving the group

rb_MovieEditor_MovieDeliveryType = New RadioButtonList
     With rb_MovieEditor_MovieDeliveryType
         .ID = [ID] & "_rb_MovieEditor_MovieDeliveryType"
         .CssClass = [CssStyle_InputControl]
         .Style.Add(HtmlTextWriterStyle.Width, "90%")
         .Style.Add(HtmlTextWriterStyle.Color, "#FFFFFF")
         .Style.Add(HtmlTextWriterStyle.FontSize, "0.8em")
     End With
        td_MovieEditor_Basic_MovieDeliveryType_Field.Controls.Add(rb_MovieEditor_MovieDeliveryType)

'// Load the Video Types in OnInit
Load_Movie_DeliveryType()
rb_MovieEditor_MovieDeliveryType.Items.Add(New ListItem("Local - Your Web Server", "STATIC"))
rb_MovieEditor_MovieDeliveryType.Items.Add(New ListItem("Streaming - Other Web Server", "STREAMING"))


Validator

$(document).ready(function () {
    
    initiateBinding();
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

});

function EndRequestHandler(sender, args) {
    initiateBinding();
}

function initiateBinding() {
    //Bind events here
    
    // Listen for the RadioButtonList Change Event
    $('[id*="_rb_MovieEditor_MovieDeliveryType"]:input:radio').blur(function () {
       rb_MovieProgramming();
        return false;
    });
});

function rb_MovieProgramming() {

    $(document).ready(function () {

        var movie_StreamingServer_Type;
        movie_StreamingServer_Type = $('[id*="_rb_MovieEditor_MovieDeliveryType"]:radio:checked').val();

        if ((movie_StreamingServer_Type != "STREAM) || (movie_StreamingServer_Type != "STATIC )) {
          // Draw a circle or something in bright red.
        }
            
                
    return true;
}
 
Share this answer
 
Comments
ghayes01 15-Jul-12 10:49am    
Thanks for the idea. Not sure that will do exactly what I need since it appears the .blur function only works when the control loses focus. With the validator, it gives my textbox the focus (in order to scroll the window so the users sees the error message).
jkirkerx 16-Jul-12 12:55pm    
I changed the way I validate, I don't do it in one shot upon submit anymore, now I do it on the fly when the form is being filled out. So I use the blur now. That way when they submit, the form transmits correctly the first time.

The secret is the word before blur, the input:radio and radio:checked, that's how you get the element tag for the group, and the option tags inside the element.

I suspected that you were having trouble validating because as individual radio buttons, it's just 1 element to validate, versus a group, which is 1 element with multiple options.

If you learn to validate the group, it will be much easier in the long run, and will produce a better product.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900