Click here to Skip to main content
15,868,016 members
Articles / Web Development / ASP.NET
Article

CustomValidator dependent on multiple controls.

Rate me:
Please Sign up or sign in to vote.
4.51/5 (25 votes)
1 Apr 20053 min read 305.2K   2.9K   63   34
Example of how to require that the user enters at least one of multiple textboxes.

Sample Image - MultiDependValidator.jpg

Introduction

ASP.NET validators are a great time saver. However, they lack the built in ability to validate multiple controls on the client side. Luckily, this is easily fixed.

Background

It is fairly easy to use something like:

ASP.NET
<asp:RequiredFieldValidator id=PhoneRequired runat="server" 
Display="Dynamic" ErrorMessage="*" ControlToValidate="Phone" />

This requires that the user fills in the Phone field. What if you have a Phone field and an Email field. You could require both fields, but you might want to allow the user to enter only one of these fields. In this case, you couldn't use RequiredFieldValidator.

Example

Requires that user enters Phone or Email. Client side validation updates when either field is changed.

Solution

Update!

I have added a user control / class based on Multi-Validator which is extended from CustomValidator, this makes creating validators that are dependent on multiple controls even easier. However, it is currently written to work with ASP.NET 2.0 beta 1 or later. See attached zip file for the source and two examples which use the classes. The following example works with ASP.NET 1.0.

Fields and CustomValidator

ASP.NET
<b>Phone: </b><asp:TextBox id="Phone" runat="server"><br />
<b>Email: </b><asp:TextBox id="Email" runat="server">
<asp:Button id="Submit" Text="Submit" /><br />

<%-- AtLeastOneContact Custom Validator --%>
<asp:CustomValidator id="AtLeastOneContact" runat="server"  
  ErrorMessage="Phone or Email Required" 
  Display="Dynamic"
  OnServerValidate="AtLeastOneContact_ServerValidate" 
  ClientValidationFunction="AtLeastOneContact_ClientValidate" />

Note: Do not set ControlToValidate. Doing so causes validation to fail when that field is empty. In ASP.NET 2.0, I recommend setting ValidateEmptyText="true".

Server Side Part

VB.NET
' Server Side Validation
Sub AtLeastOneContact_ServerValidate(ByVal source As Object, _
  ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) 
    'Requires that either Phone or Email is not empty
    If Phone.Text & Email.Text <> "" Then
        args.IsValid = true 
    Else
        args.IsValid = false 
    End If 
End Sub

Client Side Part

VBScript
<%-- Client Side Validation --%>
<script type="text/vbscript" language="vbscript">
<!--
    Sub AtLeastOneContact_ClientValidate(source, args)
        'Requires that either Phone or Email is not empty
        If document.getElementById("<%= Phone.ClientID %>").value & _
           document.getElementById("<%= Email.ClientID %>").value <> "" Then
            args.IsValid = true
        Else
            args.IsValid = false
        End If
    End Sub
'-->
</script>

Creating the dependency

JavaScript
<%-- This configures the validator to automatically--%> 
<%-- update when either of these controls is changed --%>
<script type="text/javascript">
<!--
  ValidatorHookupControlID("<%= Phone.ClientID %>", 
     document.all["<%= AtLeastOneContact.ClientID %>"]);
  ValidatorHookupControlID("<%= Email.ClientID %>", 
     document.all["<%= AtLeastOneContact.ClientID %>"]);
//-->
</script>

This is where the magic happens... This informs the built invalidation subroutines to update validation whenever one of these controls change. You can easily add as many controls as needed to a single validator's dependencies. The ValidatorHookupControlID function is part of the standard Microsoft validation scripts.

Note this code must appear after the automatically added ValidatorOnSubmit() function. This function is added to the page when you use validation controls. The best place for this script is just before the </form> tag.

I normally use Page.RegisterStartupScript to add this script to the page, however that method is harder to read and understand. I do this in the PreRender event for the CustomValidator.

Other Examples

You can use this method to create complex validations. For example, I have a drop down list with various options. One of the options is "other / see comments". The drop down list also includes a blank entry "select option". I created a validator that requires that the user enters a value for the dropdown, and if they select "other / see comments" then it requires that something is in comments.

You can validate two drop down lists against each other. For example, if you were selling clothes you could have a dropdown for the type of item and one for color selection. Then in your validator, you could show the error message if that item is not available in that color. That is you sell shirts in blue, green and red. But only sell pants in blue and green.

Demo

The zip file contains a single working aspx page. Try it out. Note that validation error messages do not display until you have updated one of the controls or try to submit. You can add Page.Validate to the Page_OnLoad event if you want validation error messages to appear immediately.

History

  • Original 02/07/05
  • Updated 02/09/05
    • I removed ValidateEmptyText="true" from CustomValidator because this property is new in ASP.NET 2.0. It is not necessary when ControlToValidateis left blank.
  • Updated 02/15/05
    • Added a usercontrol / classbased validator to the zip file, with two examples. This class based implementation requires ASP.NET 2.0.
  • Updated 04/01/05
    • Added additional ASP.NET 1.1 compliant example to the zip file.

Thanks

If you read this article then please leave a comment below.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Greesemonkey315-Oct-14 4:54
Greesemonkey315-Oct-14 4:54 
GeneralMultiValidator in FireFox [modified] Pin
hudson3611-Nov-10 4:38
hudson3611-Nov-10 4:38 
General'undefined is null' or not an object javascript error. Pin
boydd_uk9-Apr-09 6:07
boydd_uk9-Apr-09 6:07 
GeneralRe: 'undefined is null' or not an object javascript error. Pin
boydd_uk9-Apr-09 6:12
boydd_uk9-Apr-09 6:12 
GeneralSeems nice but can't make it work! Pin
ricaforrica15-Jul-08 18:31
ricaforrica15-Jul-08 18:31 
Generaleh ... I think this validates for BOTH .... Pin
macAsp14-Jul-08 4:25
macAsp14-Jul-08 4:25 
GeneralRe: eh ... I think this validates for BOTH .... Pin
DanielHac14-Jul-08 9:37
DanielHac14-Jul-08 9:37 
GeneralRe: eh ... I think this validates for BOTH .... Pin
macAsp14-Jul-08 23:24
macAsp14-Jul-08 23:24 
GeneralThis doesn't work. Pin
Christopher Hill19-Mar-08 6:13
Christopher Hill19-Mar-08 6:13 
Generalthanks Pin
atenea334-Sep-07 9:02
atenea334-Sep-07 9:02 
Generalcareful using document.all Pin
Jon Kruger18-Dec-06 3:46
Jon Kruger18-Dec-06 3:46 
GeneralRe: careful using document.all Pin
metweek15-Oct-07 12:15
metweek15-Oct-07 12:15 
GeneralReally a nice one Pin
Venkat Eswaran25-Oct-06 6:47
Venkat Eswaran25-Oct-06 6:47 
GeneralNice tip. Pin
Sachin Bhatnagar20-Jul-06 1:21
Sachin Bhatnagar20-Jul-06 1:21 
Generaleasy fast Pin
rperetz8-Jun-06 11:37
rperetz8-Jun-06 11:37 
NewsMultipleFieldsValidator for ASP.NET 2.0 Pin
Adam Tibi20-Mar-06 10:28
professionalAdam Tibi20-Mar-06 10:28 
QuestionVS2005? Pin
Bill4406023-Dec-05 5:52
Bill4406023-Dec-05 5:52 
AnswerRe: VS2005? Pin
Bill4406023-Dec-05 7:17
Bill4406023-Dec-05 7:17 
QuestionHow about multiple rows? Pin
cbwongsteve5-May-05 0:31
cbwongsteve5-May-05 0:31 
AnswerRe: How about multiple rows? Pin
Anonymous5-May-05 0:44
Anonymous5-May-05 0:44 
GeneralRe: How about multiple rows? Pin
DanielHac5-May-05 0:46
DanielHac5-May-05 0:46 
QuestionRe: How about multiple rows? Pin
mmengel13-Jun-07 16:30
mmengel13-Jun-07 16:30 
AnswerRe: How about multiple rows? Pin
kable3325-Sep-08 11:12
kable3325-Sep-08 11:12 
GeneralUse CssClass Pin
Dave Bacher12-Apr-05 3:57
Dave Bacher12-Apr-05 3:57 
GeneralRe: Use CssClass Pin
DanielHac12-Apr-05 12:25
DanielHac12-Apr-05 12:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.