473,554 Members | 2,100 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

CheckBoxList RequiredField Validator

Hello All,

I've been a taker of information from newsgroups for a long time and thought
I'd finally make a contribution back to the community whose supported me
when I've needed it. After all before commercializati on took over that was
the beauty of the Internet!

I've create a checkboxlist validator control...somet hing MS should have done
originally in my opinion, but nonetheless here it is. It's a C# control,
sort of IE specific. This is posted AS IS, I'll provide no support, but
will accept a thank you or criticism.

Happy Thanksgiving!

SOURCE FOLLOWS:

<!-- BEGIN CHECKBOXLIST REQUIRED FIELD VALIDATOR
(CheckBoxListRe quiredFieldVali dator.cs) -->

using System;
using System.Text;
using System.Web.UI;
using System.Resource s;
using System.Reflecti on;
using System.Web.UI.H tmlControls;
using System.Web.UI.W ebControls;

namespace Common.Controls
{
/// <summary>
/// Makes the associated checkboxlist control a required field
/// </summary>
public class CheckBoxListReq uiredFieldValid ator : BaseValidator
{

/// <summary>
/// Initializes a new instance of the CheckBoxListReq uiredFieldValid ator
class
/// </summary>
public CheckBoxListReq uiredFieldValid ator()
{
this.Attributes["evaluationfunc tion"] = "EvaluateCheckB oxListIsValid";
this.Attributes["initialval ue"] = "";
}

/// <summary>
/// Determines whether this validator can validate the associated control
/// </summary>
/// <returns>True </returns>
protected override bool ControlProperti esValid()
{
return true;
}

/// <summary>
/// Determines whether the checkboxlist associated to this control is
valid
/// </summary>
/// <returns>True if it is valid, otherwise false</returns>
protected override bool EvaluateIsValid ()
{
return EvaluateIsCheck ed();
}

/// <summary>
/// Determines whether a choice in the checkboxlist has been selected
/// </summary>
/// <returns>True if a choice has been selected, otherwise false</returns>
protected bool EvaluateIsCheck ed()
{
bool retVal = false;
CheckBoxList list = (CheckBoxList)F indControl(Cont rolToValidate);

foreach(ListIte m item in list.Items)
{
if (item.Selected)
{
return true;
}
}
return false;
}

/// <summary>
/// Raises the PreRender event
/// </summary>
/// <param name="e">EventA rgs that contain the event data</param>
protected override void OnPreRender(Eve ntArgs e)
{
if (this.EnableCli entScript)
{
if (!Page.IsClient ScriptBlockRegi stered("CheckBo xList"))
{
Page.RegisterCl ientScriptBlock ("CheckBoxList" , "<script
language="JavaS cript" type="text/javascript">fun ction
EvaluateCheckBo xListIsValid(va l) {var control =
document.all[val.controltova lidate];var col = control.all;if ( col != null )
{for ( i=0; i<col.length; i++ ) {if (col.item(i).ty pe == "checkbox") {if (
col.item(i).che cked ) {return true;}}}}return false;}</script>");
}
}
base.OnPreRende r(e);
}
}
}

<!-- END CHECKBOXLIST REQUIRED FIELD VALIDATOR -->

<!-- BEGIN UPDATED WEBUIVALIDATION SCRIPT (webuivalidatio n.js) -->

var Page_Validation Ver = "125";
var Page_IsValid = true;
var Page_BlockSubmi t = false;
function ValidatorUpdate Display(val) {
if (typeof(val.dis play) == "string") {
if (val.display == "None") {
return;
}
if (val.display == "Dynamic") {
val.style.displ ay = val.isvalid ? "none" : "inline";
return;
}
}
val.style.visib ility = val.isvalid ? "hidden" : "visible";
}
function ValidatorUpdate IsValid() {
var i;
for (i = 0; i < Page_Validators .length; i++) {
if (!Page_Validato rs[i].isvalid) {
Page_IsValid = false;
return;
}
}
Page_IsValid = true;
}
function ValidatorHookup ControlID(contr olID, val) {
if (typeof(control ID) != "string") {
return;
}
var ctrl = document.all[controlID];
if (typeof(ctrl) != "undefined" ) {
ValidatorHookup Control(ctrl, val);
}
else {
val.isvalid = true;
val.enabled = false;
}
}
function ValidatorHookup Control(control , val) {
if (typeof(control .tagName) == "undefined" && typeof(control. length) ==
"number") {
var i;
for (i = 0; i < control.length; i++) {
var inner = control[i];
if (typeof(inner.v alue) == "string") {
ValidatorHookup Control(inner, val);
}
}
return;
}
else if (control.tagNam e != "INPUT" && control.tagName != "TEXTAREA" &&
control.tagName != "SELECT") {
var i;
for (i = 0; i < control.childre n.length; i++) {
ValidatorHookup Control(control .children[i], val);
}
return;
}
else {
if (typeof(control .Validators) == "undefined" ) {
control.Validat ors = new Array;
var ev;
// Added type == "checkbox"
if (control.type == "radio" || control.type == "checkbox") {
ev = control.onclick ;
} else {
ev = control.onchang e;
}
if (typeof(ev) == "function" ) {
ev = ev.toString();
ev = ev.substring(ev .indexOf("{") + 1, ev.lastIndexOf( "}"));
}
else {
ev = "";
}
var func = new Function("Valid atorOnChange(); " + ev);
// Added type == "checkbox"
if (control.type == "radio" || control.type == "checkbox") {
control.onclick = func;
} else {
control.onchang e = func;
}
}
control.Validat ors[control.Validat ors.length] = val;
}
}
function ValidatorGetVal ue(id) {
var control;
control = document.all[id];
if (typeof(control .value) == "string") {
return control.value;
}
if (typeof(control .tagName) == "undefined" && typeof(control. length) ==
"number") {
var j;
for (j=0; j < control.length; j++) {
var inner = control[j];
// Added type != "checkbox"
if (typeof(inner.v alue) == "string" && (inner.type != "radio" ||
inner.type != "checkbox" || inner.status == true)) {
return inner.value;
}
}
}
else {
return ValidatorGetVal ueRecursive(con trol);
}
return "";
}
function ValidatorGetVal ueRecursive(con trol)
{
// Added type != "checkbox"
if (typeof(control .value) == "string" && (control.type != "radio" ||
inner.type != "checkbox" || control.status == true)) {
return control.value;
}
var i, val;
for (i = 0; i<control.child ren.length; i++) {
val = ValidatorGetVal ueRecursive(con trol.children[i]);
if (val != "") return val;
}
return "";
}
function Page_ClientVali date() {
var i;
for (i = 0; i < Page_Validators .length; i++) {
ValidatorValida te(Page_Validat ors[i]);
}
ValidatorUpdate IsValid();
ValidationSumma ryOnSubmit();
Page_BlockSubmi t = !Page_IsValid;
return Page_IsValid;
}
function ValidatorCommon OnSubmit() {
event.returnVal ue = !Page_BlockSubm it;
Page_BlockSubmi t = false;
}
function ValidatorEnable (val, enable) {
val.enabled = (enable != false);
ValidatorValida te(val);
ValidatorUpdate IsValid();
}
function ValidatorOnChan ge() {
var vals = event.srcElemen t.Validators;
var i;
for (i = 0; i < vals.length; i++) {
ValidatorValida te(vals[i]);
}
ValidatorUpdate IsValid();
}
function ValidatorValida te(val) {
val.isvalid = true;
if (val.enabled != false) {
if (typeof(val.eva luationfunction ) == "function") {
val.isvalid = val.evaluationf unction(val);
}
}
ValidatorUpdate Display(val);
}
function ValidatorOnLoad () {
if (typeof(Page_Va lidators) == "undefined" )
return;
var i, val;
for (i = 0; i < Page_Validators .length; i++) {
val = Page_Validators[i];
if (typeof(val.eva luationfunction ) == "string") {
eval("val.evalu ationfunction = " + val.evaluationf unction +
";");
}
if (typeof(val.isv alid) == "string") {
if (val.isvalid == "False") {
val.isvalid = false;
Page_IsValid = false;
}
else {
val.isvalid = true;
}
} else {
val.isvalid = true;
}
if (typeof(val.ena bled) == "string") {
val.enabled = (val.enabled != "False");
}
ValidatorHookup ControlID(val.c ontroltovalidat e, val);
ValidatorHookup ControlID(val.c ontrolhookup, val);
}
Page_Validation Active = true;
}
function ValidatorConver t(op, dataType, val) {
function GetFullYear(yea r) {
return (year + parseInt(val.ce ntury)) - ((year < val.cutoffyear) ? 0
: 100);
}
var num, cleanInput, m, exp;
if (dataType == "Integer") {
exp = /^\s*[-\+]?\d+\s*$/;
if (op.match(exp) == null)
return null;
num = parseInt(op, 10);
return (isNaN(num) ? null : num);
}
else if(dataType == "Double") {
exp = new RegExp("^\\s*([-\\+])?(\\d+)?(\\" + val.decimalchar +
"(\\d+))?\\s*$" );
m = op.match(exp);
if (m == null)
return null;
cleanInput = m[1] + (m[2].length>0 ? m[2] : "0") + "." + m[4];
num = parseFloat(clea nInput);
return (isNaN(num) ? null : num);
}
else if (dataType == "Currency") {
exp = new RegExp("^\\s*([-\\+])?(((\\d+)\\" + val.groupchar +
")*)(\\d+)"
+ ((val.digits > 0) ? "(\\" + val.decimalchar +
"(\\d{1," + val.digits + "}))?" : "")
+ "\\s*$");
m = op.match(exp);
if (m == null)
return null;
var intermed = m[2] + m[5] ;
cleanInput = m[1] + intermed.replac e(new RegExp("(\\" +
val.groupchar + ")", "g"), "") + ((val.digits > 0) ? "." + m[7] : 0);
num = parseFloat(clea nInput);
return (isNaN(num) ? null : num);
}
else if (dataType == "Date") {
var yearFirstExp = new
RegExp("^\\s*(( \\d{4})|(\\d{2} ))([-./])(\\d{1,2})\\4( \\d{1,2})\\s*$" );
m = op.match(yearFi rstExp);
var day, month, year;
if (m != null && (m[2].length == 4 || val.dateorder == "ymd")) {
day = m[6];
month = m[5];
year = (m[2].length == 4) ? m[2] : GetFullYear(par seInt(m[3],
10))
}
else {
if (val.dateorder == "ymd"){
return null;
}
var yearLastExp = new
RegExp("^\\s*(\ \d{1,2})([-./])(\\d{1,2})\\2( (\\d{4})|(\\d{2 }))\\s*$");
m = op.match(yearLa stExp);
if (m == null) {
return null;
}
if (val.dateorder == "mdy") {
day = m[3];
month = m[1];
}
else {
day = m[1];
month = m[3];
}
year = (m[5].length == 4) ? m[5] : GetFullYear(par seInt(m[6],
10))
}
month -= 1;
var date = new Date(year, month, day);
return (typeof(date) == "object" && year == date.getFullYea r() &&
month == date.getMonth() && day == date.getDate()) ? date.valueOf() : null;
}
else {
return op.toString();
}
}
function ValidatorCompar e(operand1, operand2, operator, val) {
var dataType = val.type;
var op1, op2;
if ((op1 = ValidatorConver t(operand1, dataType, val)) == null)
return false;
if (operator == "DataTypeCheck" )
return true;
if ((op2 = ValidatorConver t(operand2, dataType, val)) == null)
return true;
switch (operator) {
case "NotEqual":
return (op1 != op2);
case "GreaterTha n":
return (op1 > op2);
case "GreaterThanEqu al":
return (op1 >= op2);
case "LessThan":
return (op1 < op2);
case "LessThanEqual" :
return (op1 <= op2);
default:
return (op1 == op2);
}
}
function CompareValidato rEvaluateIsVali d(val) {
var value = ValidatorGetVal ue(val.controlt ovalidate);
if (ValidatorTrim( value).length == 0)
return true;
var compareTo = "";
if (null == document.all[val.controltoco mpare]) {
if (typeof(val.val uetocompare) == "string") {
compareTo = val.valuetocomp are;
}
}
else {
compareTo = ValidatorGetVal ue(val.controlt ocompare);
}
return ValidatorCompar e(value, compareTo, val.operator, val);
}
function CustomValidator EvaluateIsValid (val) {
var value = "";
if (typeof(val.con troltovalidate) == "string") {
value = ValidatorGetVal ue(val.controlt ovalidate);
if (ValidatorTrim( value).length == 0)
return true;
}
var args = { Value:value, IsValid:true };
if (typeof(val.cli entvalidationfu nction) == "string") {
eval(val.client validationfunct ion + "(val, args) ;");
}
return args.IsValid;
}
function RegularExpressi onValidatorEval uateIsValid(val ) {
var value = ValidatorGetVal ue(val.controlt ovalidate);
if (ValidatorTrim( value).length == 0)
return true;
var rx = new RegExp(val.vali dationexpressio n);
var matches = rx.exec(value);
return (matches != null && value == matches[0]);
}
function ValidatorTrim(s ) {
var m = s.match(/^\s*(\S+(\s+\S+ )*)\s*$/);
return (m == null) ? "" : m[1];
}
function RequiredFieldVa lidatorEvaluate IsValid(val) {
return (ValidatorTrim( ValidatorGetVal ue(val.controlt ovalidate)) !=
ValidatorTrim(v al.initialvalue ))
}
function RangeValidatorE valuateIsValid( val) {
var value = ValidatorGetVal ue(val.controlt ovalidate);
if (ValidatorTrim( value).length == 0)
return true;
return (ValidatorCompa re(value, val.minimumvalu e, "GreaterThanEqu al",
val) &&
ValidatorCompar e(value, val.maximumvalu e, "LessThanEqual" ,
val));
}
function ValidationSumma ryOnSubmit() {
if (typeof(Page_Va lidationSummari es) == "undefined" )
return;
var summary, sums, s;
for (sums = 0; sums < Page_Validation Summaries.lengt h; sums++) {
summary = Page_Validation Summaries[sums];
summary.style.d isplay = "none";
if (!Page_IsValid) {
if (summary.showsu mmary != "False") {
summary.style.d isplay = "";
if (typeof(summary .displaymode) != "string") {
summary.display mode = "BulletList ";
}
switch (summary.displa ymode) {
case "List":
headerSep = "<br>";
first = "";
pre = "";
post = "<br>";
final = "";
break;
case "BulletList ":
default:
headerSep = "";
first = "<ul>";
pre = "<li>";
post = "</li>";
final = "</ul>";
break;
case "SingleParagrap h":
headerSep = " ";
first = "";
pre = "";
post = " ";
final = "<br>";
break;
}
s = "";
if (typeof(summary .headertext) == "string") {
s += summary.headert ext + headerSep;
}
s += first;
for (i=0; i<Page_Validato rs.length; i++) {
if (!Page_Validato rs[i].isvalid &&
typeof(Page_Val idators[i].errormessage) == "string") {
s += pre + Page_Validators[i].errormessage + post;
}
}
s += final;
summary.innerHT ML = s;
window.scrollTo (0,0);
}
if (summary.showme ssagebox == "True") {
s = "";
if (typeof(summary .headertext) == "string") {
s += summary.headert ext + "<BR>";
}
for (i=0; i<Page_Validato rs.length; i++) {
if (!Page_Validato rs[i].isvalid &&
typeof(Page_Val idators[i].errormessage) == "string") {
switch (summary.displa ymode) {
case "List":
s += Page_Validators[i].errormessage +
"<BR>";
break;
case "BulletList ":
default:
s += " - " +
Page_Validators[i].errormessage + "<BR>";
break;
case "SingleParagrap h":
s += Page_Validators[i].errormessage + " ";
break;
}
}
}
span = document.create Element("SPAN") ;
span.innerHTML = s;
s = span.innerText;
alert(s);
}
}
}
}
<!-- END UPDATED WEBUIVALIDATION SCRIPT -->
<!-- USAGE NOTES -->

These are NOT comprehensive just intended to get you started..It assumes you
know
how to compile projects, understand namespaces and know how to register a
control.

1.) Copy CheckBoxListReq uiredFieldValid ator to a .cs class file
a.) You may need to adjust the namespace to your own

2.) Backup your webuivalidation .js file (Inetput\wwwroo t\aspnet_client
folder)

3.) Copy the webuivalidation script above over the existing file contents.
a.) I've commented the four lines that had to be changed for reference.

4.) In aspx page register the CheckBoxListReq uiredFieldValid ator using your
namespace

5.) Attach a checkboxlist control to custom validator and validate



Nov 18 '05 #1
0 7937

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3226
by: Itai | last post by:
I am attempting to create an ASP.NET Custom Validator javascript for a checkboxlist control. My goal is to limit the total number of selections to be 1 - 5 at most. My problem is that I get a null reference when I attempt to retrieve an object for an individual list item, which of course results in an "object required" error message. ...
1
10334
by: charliewest | last post by:
The MSDN documentation states that it is not possible to validate the CheckBoxList server control in ASP.NET using the RequiredFieldValidator. Is it possible to do this via the CustomValidator using client-side script? I have attempted to write javascript code, but cannot pull the value of the argument. Any ideas? Thanks.
2
2452
by: Sean | last post by:
Hi, I have 2 buttons A and B, textbox C and dropdown list D. When A is clicked, C is required field. When B is clicked, C and D are required fields. There is a dummy entry "please select" in the dropdown list. When B is clicked, D can't be the dummy option. I wonder what is the best practice for this case? I was thinking to use...
0
1948
by: S. Justin Gengo | last post by:
A few days ago in the ASP.Net forums I came across a post asking about a required field validator for the CheckBoxList component. The poster had an old link to an article he had seen online that no longer worked. It didn't take me long to find a working link to the article that did function and I posted it. Then I took a look at the C# code...
3
5444
by: Robin Day | last post by:
I run some code on the changed event of checkbox lists. Its quite simple, nothing more than showing / hiding some other parts of the page. Using Autopostback and Server side code works fine, but is far too slow, especially if the users are on modems. I need to quite simply, add some java code to the onclick event of the input tags of a...
4
1386
by: venky | last post by:
I have a question. I have two requiredfield indicators in my asp.net page and i have two buttons like getnextlead and getcustomer. I want the first requiredfieldindicator to be on for getnextleadbutton but not for getcustomer button and second indicator active for getcustomer button but not for getnextleadbutton. can anyone tell me how...
3
5518
by: Dune | last post by:
Hi, Is there anyway to get the datavaluefield from a databound checkboxlist using javascript? If not, is there any way to associate a custom attribute with the databound checkboxlist items so that the custom attribute can be accessed using javascript? Cheers
3
6336
by: tshad | last post by:
Can you use a Required Validator on a CheckBoxList? You can on a RadioButtonList. But when I try on my CheckBoxList I get the error: Control 'RFPServiceTypes' referenced by the ControlToValidate property of 'ServiceTypesCheck' cannot be validated <asp:CheckBoxList id="RFPServiceTypes" CellPadding="0" CellSpacing="0"
1
984
by: KA Kueh | last post by:
Dear all, Does any one know why on earth does MS leave out validator for checkbox and checkboxlist? Even the newest VS 2008 is left without one. Thanks. Regards, Kueh.
0
7605
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7530
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8047
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7570
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7893
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6156
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5162
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3570
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1141
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.