Click here to Skip to main content
11,634,815 members (67,906 online)
Click here to Skip to main content

Multiple Fields Validator - An ASP.NET Validation Control

, 7 Apr 2006 Ms-PL 488.2K 4.9K 134
Rate this:
Please Sign up or sign in to vote.
Discussing the MultipleFieldsValidator that validates a group of fields in which at least one is required, like phone number, mobile phone number, or email. It inherits the BaseValidator and uses some new cool ASP.NET 2.0 features.

Sample Image

Introduction

In an ideal world, web users don't need to authenticate because they are trustworthy, no try-catch because there wouldn't be any bug or unexpected behavior, and you wouldn't be using web validators because users will be submitting valid entries. But since we are not living in that world, I hope we would some time, you might find this validator useful, so bear with me.

Developing with ASP.NET, I've encountered many cases when you only need one field to be filled out of many given fields. To validate in such cases, I used to have a custom validator, or a client-script, or some times did server-side validation only.

The problem with a custom validator, and all other ASP.NET validators, is that they are mainly designed to handle one or two fields. Also, you need to write custom server-side and client-side code, or maybe copy and paste code, every time you encounter validating multiple fields. To solve this, I have made this light multiple-controls validator, and got use of the new ASP.NET 2.0 features.

Background

Even with ASP.NET 2.0, a lot of valuable validation controls are missing, especially those for multiple-fields validation. Peter Blum has created a set of commercial controls called Professional Validation And More to fill this gap and he, when answering my forum post, gave me the idea of implementing my own validator.

I have also found a good article on CodeProject by Daniel Hacquebord on CustomValidator dependent on multiple controls that addresses a similar need, however, this validation control has the following advantages:

  1. Doesn't require writing any client or server-side code. Just drop it on the page and assign it the controls that you want to validate.
  2. HTML/XHTML compatible. It assigns additional attributes with JavaScript rather than adding them directly to the span tag. That is, it uses JavaScript document["MyMultipleFieldsValidator"].condition = "OR" rather than the HTML <span id="MyMultipleFieldsValidator" condition = "OR">.
  3. Uses a .js resource file to register the client-side code rather than writing the client-side code in every page that requires this control.
  4. Inherits directly from BaseValidator versus CusomValidator, thus, gaining a tiny extra performance.

There is another good article on CodeProject that gave me some inspiration, called RequiredIfValidator - Extending from the BaseValidator class about a validator that validates another field based on the selection of a drop down list.

Using the Code

BaseValidator, the base of this control, is mainly made to handle one control so I had to disable some properties that is meant to validate a single control. I had to shadow the ControlToValidate and SetFocusOnError properties and hide them from the designer and the Visual Studio editor.

[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public new bool SetFocusOnError {
    get {
        return false;
    }
    set {
        throw new NotSupportedException("SetFocusOnError is not supported.");
    }
}

[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public new string ControlToValidate {
    get {
        return string.Empty;
    }
    set {
        throw new NotSupportedException("ControlToValidate is not supported.");
    }
}

In the AddAttributesToRender, I am using the ASP.NET 2.0 RegisterExpandoAttribute method to add attributes, using JavaScript, to the <span> tag generated by the validator rather than adding them statically, hence, keeping it HTML/XHTML friendly.

if(this.RenderUplevel) {
    string clientID = this.ClientID;
    Page.ClientScript.RegisterExpandoAttribute(clientID, 
        "evaluationfunction", 
        "MultipleFieldsValidatorEvaluateIsValid");
    Page.ClientScript.RegisterExpandoAttribute(clientID, 
        "controlstovalidate", 
        this.GenerateClientSideControlsToValidate());
    Page.ClientScript.RegisterExpandoAttribute(clientID, 
        "condition",
        PropertyConverter.EnumToString(typeof(Conditions), Condition));
}

In the OnPreRender, I've used the new ASP.NET 2.0 method RegisterClientScriptResource to add my embedded .js file to the page. There is a good article by Gary Dryden on CodeProject called WebResource ASP.NET 2.0 explained that deals with this subject.

protected override void OnPreRender(EventArgs e) {
    base.OnPreRender(e);
    if (base.RenderUplevel) {
        this.Page.ClientScript.RegisterClientScriptResource(
            typeof(MultipleFieldsValidator),
            "AdamTibi.Web.UI.Validators.WebUIValidationExtended.js");
    }
}

Using the Validator

To use this validator from your Visual Studio IDE, you need to add the provided .dll to the toolbox. For more information on this, check the MSDN documentation.

After dropping the validator on a webform, all you need to do is to set the ControlsToValidate property, from the Properties window, to point to the controls that you want to validate. This summarizes the generated code; however, the demo attached with the article has more examples.

The Condition property, which is set to OR by default, sets the condition that you want to apply when validating multiple fields. So, OR ensures one of the fields is filled, XOR ensures one of the fields is filled but not all of them.

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Register TagPrefix="atv" Namespace="AdamTibi.Web.UI.Validators" 
    Assembly="AdamTibi.Web.UI.Validators" %>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtPhone" runat="server"></asp:TextBox>
<asp:TextBox ID="txtMobile" runat="server"></asp:TextBox>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<atv:MultipleFieldsValidator ID="mfv" runat="server" Condition="OR"
    ControlsToValidate="txtPhone,txtMobile,txtEmail">
    fill at least one field</atv:MultipleFieldsValidator>
</form>
</body>
</html>

Limitations

I've only tested the validator on IE 6 and Firefox 1.5; however, I am not using any weird JavaScript so it should work on other browsers as well. Please let me know if it worked for you.

I only need the validator to check TextBox fields so I didn't check it with other types of controls; however, in theory, it should work fine. Also, let me know if you are getting any problems.

Conclusion

I hope I made someone’s day. If you like this article then please remember to vote. If you have any suggestions, bugs, or enhancements then hit me with it!

History

  • 10 March 2006 - First version.
  • 04 April 2006 - Now works with Firefox.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)

Share

About the Author

Adam Tibi
Architect
United Kingdom United Kingdom
Passionate about refining software practices, promoting self-motivated teams and orchestrating agile projects that hit the deadline.
Lives in London, UK and works as a .NET architect consultant in the City.

Need a pro service to help your organisation? Contact me via my website www.AdamTibi.net.

You may also be interested in...

Comments and Discussions

 
QuestionPermission denied error issues Pin
TecNQ29-Oct-14 15:27
professionalTecNQ29-Oct-14 15:27 
AnswerRe: Permission denied error issues Pin
TecNQ29-Oct-14 18:56
professionalTecNQ29-Oct-14 18:56 
GeneralRe: Permission denied error issues Pin
Adam Tibi31-Oct-14 0:37
professionalAdam Tibi31-Oct-14 0:37 
Question.NET 4.0 compatibility Pin
Member 793265329-Aug-12 6:13
memberMember 793265329-Aug-12 6:13 
NewsGreat Job! Pin
Jani Giannoudis16-Apr-12 18:31
mvpJani Giannoudis16-Apr-12 18:31 
GeneralMy vote of 5 Pin
prabhakamaji29-Nov-11 23:39
memberprabhakamaji29-Nov-11 23:39 
QuestionWhat About a check box and a text box? Pin
metapro6-Jun-11 5:46
membermetapro6-Jun-11 5:46 
GeneralValidateEmptyText property a possibility? Pin
CWells127-Apr-11 12:23
memberCWells127-Apr-11 12:23 
GeneralMy vote of 5 Pin
CWells127-Apr-11 12:21
memberCWells127-Apr-11 12:21 
GeneralMy vote of 5 Pin
Member 412980623-Feb-11 3:27
memberMember 412980623-Feb-11 3:27 
GeneralRevalidate on key press Pin
dazipe17-Feb-11 21:11
memberdazipe17-Feb-11 21:11 
GeneralMultiple RadComboBox validation :S Pin
Member 225598810-Aug-10 12:43
memberMember 225598810-Aug-10 12:43 
GeneralChange c# to vb.net Pin
gensy623525-Jul-10 23:32
membergensy623525-Jul-10 23:32 
Jokehelpful.... Pin
leopard-saleh1-Mar-10 9:28
memberleopard-saleh1-Mar-10 9:28 
GeneralRe: helpful.... Pin
Adam Tibi2-Mar-10 0:13
memberAdam Tibi2-Mar-10 0:13 
I am glad it helped Smile | :)
Make it simple, as simple as possible, but not simpler.

Questionit is not validating properly Pin
Sreedhar Mallipedda10-Feb-10 5:23
memberSreedhar Mallipedda10-Feb-10 5:23 
GeneralNice Work! Pin
Joshua Blackstone1-Feb-10 4:43
memberJoshua Blackstone1-Feb-10 4:43 
GeneralThank you Pin
simonmharris27-Jan-10 21:30
membersimonmharris27-Jan-10 21:30 
GeneralRe: Thank you Pin
Adam Tibi31-Jan-10 23:16
memberAdam Tibi31-Jan-10 23:16 
GeneralJust what I needed Pin
jmar215-Dec-09 10:07
memberjmar215-Dec-09 10:07 
GeneralNice work - re-validate on loss of focus. Pin
John Blogs24-Nov-09 18:18
memberJohn Blogs24-Nov-09 18:18 
GeneralRe: Nice work - re-validate on loss of focus. Pin
Adam Tibi26-Nov-09 1:06
memberAdam Tibi26-Nov-09 1:06 
GeneralCHANGE TO ONPRERENDER METHOD FOR FRAMEWORK 3.5 Pin
JacquiF20-Nov-09 2:51
memberJacquiF20-Nov-09 2:51 
GeneralRe: CHANGE TO ONPRERENDER METHOD FOR FRAMEWORK 3.5 Pin
Adam Tibi26-Nov-09 1:08
memberAdam Tibi26-Nov-09 1:08 
QuestionInitialValue Pin
grenadier1-Sep-09 9:47
membergrenadier1-Sep-09 9:47 
AnswerRe: InitialValue Pin
Adam Tibi1-Sep-09 11:47
memberAdam Tibi1-Sep-09 11:47 
GeneralRe: InitialValue Pin
grenadier1-Sep-09 12:00
membergrenadier1-Sep-09 12:00 
GeneralAdded lost focus check Pin
jjhale81112-Jun-09 6:25
memberjjhale81112-Jun-09 6:25 
GeneralRe: Added lost focus check Pin
Adam Tibi15-Jun-09 5:00
memberAdam Tibi15-Jun-09 5:00 
GeneralWell thought out Pin
Matt Sollars29-May-09 4:42
memberMatt Sollars29-May-09 4:42 
GeneralRe: Well thought out Pin
Adam Tibi29-May-09 5:52
memberAdam Tibi29-May-09 5:52 
GeneralMultiple Control Validation Pin
jdalnes27-Feb-09 11:12
memberjdalnes27-Feb-09 11:12 
GeneralRe: Multiple Control Validation Pin
Adam Tibi2-Mar-09 5:31
memberAdam Tibi2-Mar-09 5:31 
GeneralControl properties lost on postback Pin
Member 389014712-Dec-08 8:25
memberMember 389014712-Dec-08 8:25 
GeneralAjax Pin
cf200624-Nov-08 9:34
membercf200624-Nov-08 9:34 
GeneralRe: Ajax Pin
Matt Sollars29-May-09 9:30
memberMatt Sollars29-May-09 9:30 
GeneralRe: Ajax Pin
Montydog11-Aug-10 20:17
memberMontydog11-Aug-10 20:17 
GeneralRe: Ajax Pin
Adam Tibi11-Aug-10 21:23
memberAdam Tibi11-Aug-10 21:23 
GeneralRe: Ajax Pin
Matt Sollars12-Aug-10 3:11
memberMatt Sollars12-Aug-10 3:11 
GeneralThanks! Pin
Jane Williams6-Oct-08 4:06
memberJane Williams6-Oct-08 4:06 
GeneralRe: Thanks! Pin
Adam Tibi8-Oct-08 8:12
memberAdam Tibi8-Oct-08 8:12 
GeneralRe: Thanks! Pin
Jane Williams30-Oct-08 4:31
memberJane Williams30-Oct-08 4:31 
GeneralRe: Thanks! Pin
Adam Tibi31-Oct-08 14:21
memberAdam Tibi31-Oct-08 14:21 
GeneralRe: Thanks! Pin
Jane Williams4-Nov-08 0:57
memberJane Williams4-Nov-08 0:57 
Question[Message Deleted] Pin
jay123456789024-Sep-08 4:21
memberjay123456789024-Sep-08 4:21 
AnswerRe: help... Pin
Adam Tibi24-Sep-08 8:12
memberAdam Tibi24-Sep-08 8:12 
GeneralNice work and a huge help! Pin
Stevishere9-Sep-08 11:58
memberStevishere9-Sep-08 11:58 
GeneralRe: Nice work and a huge help! Pin
Adam Tibi9-Sep-08 23:50
memberAdam Tibi9-Sep-08 23:50 
GeneralThanks a lot Pin
blue_nerve26-Aug-08 20:03
memberblue_nerve26-Aug-08 20:03 
GeneralRe: Thanks a lot Pin
Adam Tibi26-Aug-08 22:49
memberAdam Tibi26-Aug-08 22:49 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150728.1 | Last Updated 7 Apr 2006
Article Copyright 2006 by Adam Tibi
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid