472,342 Members | 1,298 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,342 software developers and data experts.

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 commercialization took over that was
the beauty of the Internet!

I've create a checkboxlist validator control...something 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
(CheckBoxListRequiredFieldValidator.cs) -->

using System;
using System.Text;
using System.Web.UI;
using System.Resources;
using System.Reflection;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

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

/// <summary>
/// Initializes a new instance of the CheckBoxListRequiredFieldValidator
class
/// </summary>
public CheckBoxListRequiredFieldValidator()
{
this.Attributes["evaluationfunction"] = "EvaluateCheckBoxListIsValid";
this.Attributes["initialvalue"] = "";
}

/// <summary>
/// Determines whether this validator can validate the associated control
/// </summary>
/// <returns>True</returns>
protected override bool ControlPropertiesValid()
{
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 EvaluateIsChecked();
}

/// <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 EvaluateIsChecked()
{
bool retVal = false;
CheckBoxList list = (CheckBoxList)FindControl(ControlToValidate);

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

/// <summary>
/// Raises the PreRender event
/// </summary>
/// <param name="e">EventArgs that contain the event data</param>
protected override void OnPreRender(EventArgs e)
{
if (this.EnableClientScript)
{
if (!Page.IsClientScriptBlockRegistered("CheckBoxList "))
{
Page.RegisterClientScriptBlock("CheckBoxList", "<script
language="JavaScript" type="text/javascript">function
EvaluateCheckBoxListIsValid(val) {var control =
document.all[val.controltovalidate];var col = control.all;if ( col != null )
{for ( i=0; i<col.length; i++ ) {if (col.item(i).type == "checkbox") {if (
col.item(i).checked ) {return true;}}}}return false;}</script>");
}
}
base.OnPreRender(e);
}
}
}

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

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

var Page_ValidationVer = "125";
var Page_IsValid = true;
var Page_BlockSubmit = false;
function ValidatorUpdateDisplay(val) {
if (typeof(val.display) == "string") {
if (val.display == "None") {
return;
}
if (val.display == "Dynamic") {
val.style.display = val.isvalid ? "none" : "inline";
return;
}
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
}
function ValidatorUpdateIsValid() {
var i;
for (i = 0; i < Page_Validators.length; i++) {
if (!Page_Validators[i].isvalid) {
Page_IsValid = false;
return;
}
}
Page_IsValid = true;
}
function ValidatorHookupControlID(controlID, val) {
if (typeof(controlID) != "string") {
return;
}
var ctrl = document.all[controlID];
if (typeof(ctrl) != "undefined") {
ValidatorHookupControl(ctrl, val);
}
else {
val.isvalid = true;
val.enabled = false;
}
}
function ValidatorHookupControl(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.value) == "string") {
ValidatorHookupControl(inner, val);
}
}
return;
}
else if (control.tagName != "INPUT" && control.tagName != "TEXTAREA" &&
control.tagName != "SELECT") {
var i;
for (i = 0; i < control.children.length; i++) {
ValidatorHookupControl(control.children[i], val);
}
return;
}
else {
if (typeof(control.Validators) == "undefined") {
control.Validators = new Array;
var ev;
// Added type == "checkbox"
if (control.type == "radio" || control.type == "checkbox") {
ev = control.onclick;
} else {
ev = control.onchange;
}
if (typeof(ev) == "function" ) {
ev = ev.toString();
ev = ev.substring(ev.indexOf("{") + 1, ev.lastIndexOf("}"));
}
else {
ev = "";
}
var func = new Function("ValidatorOnChange(); " + ev);
// Added type == "checkbox"
if (control.type == "radio" || control.type == "checkbox") {
control.onclick = func;
} else {
control.onchange = func;
}
}
control.Validators[control.Validators.length] = val;
}
}
function ValidatorGetValue(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.value) == "string" && (inner.type != "radio" ||
inner.type != "checkbox" || inner.status == true)) {
return inner.value;
}
}
}
else {
return ValidatorGetValueRecursive(control);
}
return "";
}
function ValidatorGetValueRecursive(control)
{
// 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.children.length; i++) {
val = ValidatorGetValueRecursive(control.children[i]);
if (val != "") return val;
}
return "";
}
function Page_ClientValidate() {
var i;
for (i = 0; i < Page_Validators.length; i++) {
ValidatorValidate(Page_Validators[i]);
}
ValidatorUpdateIsValid();
ValidationSummaryOnSubmit();
Page_BlockSubmit = !Page_IsValid;
return Page_IsValid;
}
function ValidatorCommonOnSubmit() {
event.returnValue = !Page_BlockSubmit;
Page_BlockSubmit = false;
}
function ValidatorEnable(val, enable) {
val.enabled = (enable != false);
ValidatorValidate(val);
ValidatorUpdateIsValid();
}
function ValidatorOnChange() {
var vals = event.srcElement.Validators;
var i;
for (i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i]);
}
ValidatorUpdateIsValid();
}
function ValidatorValidate(val) {
val.isvalid = true;
if (val.enabled != false) {
if (typeof(val.evaluationfunction) == "function") {
val.isvalid = val.evaluationfunction(val);
}
}
ValidatorUpdateDisplay(val);
}
function ValidatorOnLoad() {
if (typeof(Page_Validators) == "undefined")
return;
var i, val;
for (i = 0; i < Page_Validators.length; i++) {
val = Page_Validators[i];
if (typeof(val.evaluationfunction) == "string") {
eval("val.evaluationfunction = " + val.evaluationfunction +
";");
}
if (typeof(val.isvalid) == "string") {
if (val.isvalid == "False") {
val.isvalid = false;
Page_IsValid = false;
}
else {
val.isvalid = true;
}
} else {
val.isvalid = true;
}
if (typeof(val.enabled) == "string") {
val.enabled = (val.enabled != "False");
}
ValidatorHookupControlID(val.controltovalidate, val);
ValidatorHookupControlID(val.controlhookup, val);
}
Page_ValidationActive = true;
}
function ValidatorConvert(op, dataType, val) {
function GetFullYear(year) {
return (year + parseInt(val.century)) - ((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(cleanInput);
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.replace(new RegExp("(\\" +
val.groupchar + ")", "g"), "") + ((val.digits > 0) ? "." + m[7] : 0);
num = parseFloat(cleanInput);
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(yearFirstExp);
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(parseInt(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(yearLastExp);
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(parseInt(m[6],
10))
}
month -= 1;
var date = new Date(year, month, day);
return (typeof(date) == "object" && year == date.getFullYear() &&
month == date.getMonth() && day == date.getDate()) ? date.valueOf() : null;
}
else {
return op.toString();
}
}
function ValidatorCompare(operand1, operand2, operator, val) {
var dataType = val.type;
var op1, op2;
if ((op1 = ValidatorConvert(operand1, dataType, val)) == null)
return false;
if (operator == "DataTypeCheck")
return true;
if ((op2 = ValidatorConvert(operand2, dataType, val)) == null)
return true;
switch (operator) {
case "NotEqual":
return (op1 != op2);
case "GreaterThan":
return (op1 > op2);
case "GreaterThanEqual":
return (op1 >= op2);
case "LessThan":
return (op1 < op2);
case "LessThanEqual":
return (op1 <= op2);
default:
return (op1 == op2);
}
}
function CompareValidatorEvaluateIsValid(val) {
var value = ValidatorGetValue(val.controltovalidate);
if (ValidatorTrim(value).length == 0)
return true;
var compareTo = "";
if (null == document.all[val.controltocompare]) {
if (typeof(val.valuetocompare) == "string") {
compareTo = val.valuetocompare;
}
}
else {
compareTo = ValidatorGetValue(val.controltocompare);
}
return ValidatorCompare(value, compareTo, val.operator, val);
}
function CustomValidatorEvaluateIsValid(val) {
var value = "";
if (typeof(val.controltovalidate) == "string") {
value = ValidatorGetValue(val.controltovalidate);
if (ValidatorTrim(value).length == 0)
return true;
}
var args = { Value:value, IsValid:true };
if (typeof(val.clientvalidationfunction) == "string") {
eval(val.clientvalidationfunction + "(val, args) ;");
}
return args.IsValid;
}
function RegularExpressionValidatorEvaluateIsValid(val) {
var value = ValidatorGetValue(val.controltovalidate);
if (ValidatorTrim(value).length == 0)
return true;
var rx = new RegExp(val.validationexpression);
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 RequiredFieldValidatorEvaluateIsValid(val) {
return (ValidatorTrim(ValidatorGetValue(val.controltovali date)) !=
ValidatorTrim(val.initialvalue))
}
function RangeValidatorEvaluateIsValid(val) {
var value = ValidatorGetValue(val.controltovalidate);
if (ValidatorTrim(value).length == 0)
return true;
return (ValidatorCompare(value, val.minimumvalue, "GreaterThanEqual",
val) &&
ValidatorCompare(value, val.maximumvalue, "LessThanEqual",
val));
}
function ValidationSummaryOnSubmit() {
if (typeof(Page_ValidationSummaries) == "undefined")
return;
var summary, sums, s;
for (sums = 0; sums < Page_ValidationSummaries.length; sums++) {
summary = Page_ValidationSummaries[sums];
summary.style.display = "none";
if (!Page_IsValid) {
if (summary.showsummary != "False") {
summary.style.display = "";
if (typeof(summary.displaymode) != "string") {
summary.displaymode = "BulletList";
}
switch (summary.displaymode) {
case "List":
headerSep = "<br>";
first = "";
pre = "";
post = "<br>";
final = "";
break;
case "BulletList":
default:
headerSep = "";
first = "<ul>";
pre = "<li>";
post = "</li>";
final = "</ul>";
break;
case "SingleParagraph":
headerSep = " ";
first = "";
pre = "";
post = " ";
final = "<br>";
break;
}
s = "";
if (typeof(summary.headertext) == "string") {
s += summary.headertext + headerSep;
}
s += first;
for (i=0; i<Page_Validators.length; i++) {
if (!Page_Validators[i].isvalid &&
typeof(Page_Validators[i].errormessage) == "string") {
s += pre + Page_Validators[i].errormessage + post;
}
}
s += final;
summary.innerHTML = s;
window.scrollTo(0,0);
}
if (summary.showmessagebox == "True") {
s = "";
if (typeof(summary.headertext) == "string") {
s += summary.headertext + "<BR>";
}
for (i=0; i<Page_Validators.length; i++) {
if (!Page_Validators[i].isvalid &&
typeof(Page_Validators[i].errormessage) == "string") {
switch (summary.displaymode) {
case "List":
s += Page_Validators[i].errormessage +
"<BR>";
break;
case "BulletList":
default:
s += " - " +
Page_Validators[i].errormessage + "<BR>";
break;
case "SingleParagraph":
s += Page_Validators[i].errormessage + " ";
break;
}
}
}
span = document.createElement("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 CheckBoxListRequiredFieldValidator to a .cs class file
a.) You may need to adjust the namespace to your own

2.) Backup your webuivalidation.js file (Inetput\wwwroot\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 CheckBoxListRequiredFieldValidator using your
namespace

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



Nov 18 '05 #1
0 7814

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

Similar topics

1
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...
1
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...
2
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...
0
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...
3
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...
4
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...
3
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...
3
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...
1
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....
0
by: concettolabs | last post by:
In today's business world, businesses are increasingly turning to PowerApps to develop custom business applications. PowerApps is a powerful tool...
0
better678
by: better678 | last post by:
Question: Discuss your understanding of the Java platform. Is the statement "Java is interpreted" correct? Answer: Java is an object-oriented...
0
by: teenabhardwaj | last post by:
How would one discover a valid source for learning news, comfort, and help for engineering designs? Covering through piles of books takes a lot of...
0
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific...

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.