Home
 Index > ASP.NET Web Applications > How to use a CustomValidator to validate one We...

ASP.NET Web Applications:  FormView , DetailsView , Validation

How to use a CustomValidator to validate one Web control only if a checkbox or radiobutton is checked.

This article demonstrates how to create client-side and server-side custom validation in a FormView.

Added on 12 Jul 2008

Scenarios:

Scenario Summary:
The objective is to require data in a text field only when a certain radio button is checked. If the radio button is not checked, the textbox does not need to be validated.
Scenario Details:

The form asks the users to select their preference for deleting records.  The options are:

  • Manual deletions
  • Delete completed tasks older than [x] number of days.
  • Keep only the last [x] number of completed items.

The bullets represent radiobuttons.  The [x]'s represent textboxes where the user must enter an integer in a certain range.

Added on 12 Jul 2008

Solution Summary:
The following is the code to handle the above scenario.
Solution Details:

JavaScript (i.e., ClientValidationFunction):

// custom validators take two arguments (sender and args)
function RequireDays(sender, args) {
      
//client side code requires client id!
     var tbDays = document.getElementById('ctl00_ContentPlaceHolder1_fv_Member_tbDays'); 
    
var rbDays = document.getElementById('ctl00_ContentPlaceHolder1_fv_Member_rbDays');
      
//if the radio button is not checked, it is valid
     var isValid = (! rbDays.checked); 
    
var value = tbDays.value;
    
if (rbDays.checked == true
     {
          
//check length for required field
         if(value.length > 0) 
         {
             
//ensure that we have a valid integer
    
        if(isNumeric(value)) 
             {            
                 
//ensure the integer is in the range
                 if(value > -1 && value < 31) {
                     isValid = 
true;
                }
             }
         }        
     }
     args.IsValid = isValid;
}
//repeat the process for the other radiobutton
function RequireItems(sender, args) {
    
var tbItems = document.getElementById('ctl00_ContentPlaceHolder1_fv_Member_tbItems');
    
var rbItems = document.getElementById('ctl00_ContentPlaceHolder1_fv_Member_rbItems');
    
var isValid = (! rbItems.checked);
    
var value = tbItems.value;
    
if (rbItems.checked == true
     {
         
if(value.length > 0) 
         {
             
if(isNumeric(value)) 
             {
                 
if(value > -1 && value < 101) {
                     isValid = 
true;
                }
             }
         }        
     }
     args.IsValid = isValid;
}
//function for checking for numeric data
function isNumeric(val) {
    
var ValidChars = "0123456789"
    
var Char;
    
for (i = 0; i < val.length; i++) {
          Char = val.charAt(i);
         
if (ValidChars.indexOf(Char) == -1) {
              
return false;
          }
     }
    
return true;
}



VB (OnServerValidate function):


#Region "Custom validation"

    Public Sub RequireDays(ByVal source As ObjectByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
        
Dim tbDays As TextBox = CType(fv_Member.Row.FindControl("tbDays"), TextBox)
        
Dim rbDays As RadioButton = CType(fv_Member.Row.FindControl("rbDays"), RadioButton)
        
Dim isValid As Boolean = Not rbDays.Checked
        
If rbDays.Checked Then
            isValid = False
            If tbDays.Text.Length > 0 Then
                If IsNumeric(tbDays.Text) Then
                    Dim i As Int32 = Convert.ToInt32(tbDays.Text)
                    
If i > -1 And i < 31 Then
                        isValid = True
                    End If
                End If
            End If
        End If
        args.IsValid = isValid
    
End Sub

    Public Sub RequireItems(ByVal source As ObjectByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
        
Dim tbItems As TextBox = CType(fv_Member.Row.FindControl("tbItems"), TextBox)
        
Dim rbItems As RadioButton = CType(fv_Member.Row.FindControl("rbItems"), RadioButton)
        
Dim isValid As Boolean = Not rbItems.Checked
        
If rbItems.Checked Then
            isValid = False
            If tbItems.Text.Length > 0 Then
                If IsNumeric(tbItems.Text) Then
                    Dim i As Int32 = Convert.ToInt32(tbItems.Text)
                    
If i > -1 And i < 101 Then
                        isValid = True
                    End If
                End If
            End If
        End If
        args.IsValid = isValid
    
End Sub

#End
 Region


Relevant ASPX code:

<tr>
    <td style="font-weight:bold;"></td>
    <td width="100%" class="fieldcaption">Deletion Preference:</td>
    <td>
        <asp:RadioButton ID="rbDays" runat="server" GroupName="Deletion" Checked="True" />Older than
        
<asp:TextBox ID="tbDays" runat="server" MaxLength="2" Width="31px" TabIndex="2" style="text-aligncenter;">7</asp:TextBox>&nbsp;days <asp:CustomValidator ControlToValidate="tbDays" ID="CustomValidator1" ClientValidationFunction="RequireDays" OnServerValidate="RequireDays" runat="server" Display="Dynamic" Text="*" ValidationGroup="MemberForm" ErrorMessage="Enter an integer between 0 and 30 for the number of days to keep deleted records."></asp:CustomValidator></td>
</
tr>
<
tr>
    <td style="font-weight:bold;">&nbsp;</td>
    <td style="font-weight:bold;">&nbsp;</td>
    <td>
        <asp:RadioButton ID="rbItems" runat="server" GroupName="Deletion" />
        Save only
        
<asp:TextBox ID="tbItems" runat="server" MaxLength="3" Width="31px" TabIndex="2" style="text-aligncenter;">10</asp:TextBox>&nbsp;items <asp:CustomValidator ControlToValidate="tbItems" ID="CustomValidator2" ClientValidationFunction="RequireItems" OnServerValidate="RequireItems" runat="server" Display="Dynamic" Text="*" ValidationGroup="MemberForm" ErrorMessage="Enter an integer between 0 and 100 for the number of deleted items to keep in the database."></asp:CustomValidator></td>
</
tr>
<
tr>
    <td style="font-weight:bold;">&nbsp;</td>
    <td style="font-weight:bold;">&nbsp;</td>
    <td><asp:RadioButton ID="rbAction" runat="server" GroupName="Deletion" Text="Keep until I delete" /></td>
</
tr>
Was this solution useful? Yes No Added on 12 Jul 2008
Rating: 

Copyright 2010 © E-Centric, Inc. | Terms of Use