Posts Tagged ‘ASP.NET Validator Controls’

A ValidationSummary control is displayed when the IsValid property of the page is false. It “polls” each of the validation controls on the page and aggregates the text messages exposed by each.  It does this through the Page.Validators collection; each validation control is added to this collection, and the validation summary can use this to determine which validators have errors.

When the user’s input is processed (for example, when the form is submitted), the Web Forms framework passes the user’s entry to the associated validation control or controls based on the ValidationGroup property. The validation controls test the user’s input and set a property to indicate whether the entry passed the validation test. After all validation controls have been processed, the IsValid property on the page is set; if any of the controls shows that a validation check failed, the entire page is set to invalid.

The following sample illustrates displaying errors with a ValidationSummary

<form id=”form1″ runat=”server”>
<div>
Age:<br />
<asp:TextBox runat=”server” id=”txt3″ />
<asp:RequiredFieldValidator runat=”server” id=”reqtxt3″ controltovalidate=”txt3″
errormessage=”Age” ValidationGroup=”234″ Display=”Static”>*</asp:RequiredFieldValidator>
<asp:RangeValidator runat=”server” id=”rangetxt3″ controltovalidate=”txt3″
errormessage=”Age – enter valid value (Between 1 to 120)”
MaximumValue=”120″ MinimumValue=”1″  Type=”Integer” ValidationGroup=”234″ Display=”Static”>*</asp:RangeValidator>
<br /><br />

Name:<br />
<asp:TextBox runat=”server” id=”txt1″ />
<asp:RequiredFieldValidator runat=”server” id=”reqtxt1″ controltovalidate=”txt1″ errormessage=”Name” ValidationGroup=”234″ Display=”Static”>*</asp:RequiredFieldValidator>
<br /><br />

<asp:Button runat=”server” id=”btnSubmit3″ text=”Ok” ValidationGroup=”234″/>
</div>

<div>
<asp:ValidationSummary ID=”valSum” runat=”server”
HeaderText=”You must enter a value in the following fields:”
Font-Names=”verdana”
Font-Size=”12″
DisplayMode=”BulletList”
ValidationGroup=”234″ />
</div>
</form>

References –

http://wiki.asp.net/page.aspx/237/validation-controls/
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/validation/default.aspx

Advertisements

ListValidator.cs Code

public class ListValidator : BaseValidator
{
public ListValidator()
{}

protected override bool ControlPropertiesValid()
{
Control ctrl = FindControl(ControlToValidate) as ListControl;
return (ctrl != null);
}

protected override bool EvaluateIsValid()
{
return this.CheckIfItemIsChecked();
}

protected bool CheckIfItemIsChecked()
{
ListControl listItemValidate = ((ListControl)this.FindControl(this.ControlToValidate));
foreach (ListItem listItem in listItemValidate.Items)
{
if (listItem.Selected == true)
return true;
}
return false;
}

protected override void OnPreRender(EventArgs e)
{
// Determines whether the validation control can be rendered
// for a newer (“uplevel”) browser.
// check if client-side validation is enabled.
if (this.DetermineRenderUplevel() && this.EnableClientScript)
{
Page.ClientScript.RegisterExpandoAttribute(this.ClientID, “evaluationfunction”, “CheckIfListChecked”);
this.CreateJavaScript();
}
base.OnPreRender(e);
}

protected void CreateJavaScript()
{
StringBuilder sb = new StringBuilder();
sb.Append(@”<script type=””text/javascript””>function CheckIfListChecked(ctrl){“);
sb.Append(@”var chkBoxList = document.getElementById(document.getElementById(ctrl.id).controltovalidate);”);
sb.Append(@”var chkBoxCount= chkBoxList.getElementsByTagName(“”input””);”);
sb.Append(@”for(var i=0;i<chkBoxCount.length;i++){“);
sb.Append(@”if(chkBoxCount.item(i).checked){“);
sb.Append(@”return true; }”);
sb.Append(@”}return false; “);
sb.Append(@”}</script>”);
Page.ClientScript.RegisterClientScriptBlock(GetType(), “JSScript”, sb.ToString());
}
}

Custom Validator Control – Usage – Client Side

<%@ Register TagPrefix=”CLV” Namespace=”WebApplication1.Concepts.Validators” assembly=”WebApplication1″%>

<form id=”form1″ runat=”server”>
<asp:CheckBoxList ID=”CheckBoxList1″ runat=”server”></asp:CheckBoxList>
<CLV:ListValidator runat=”server” ID=”custLstVal” ControlToValidate=”CheckBoxList1″ ErrorMessage=”At least one item in the checkboxlist should be checked”
EnableClientScript=”true”/>
<asp:RadioButtonList ID=”RadioButtonList1″ runat=”server”></asp:RadioButtonList>
<CLV:ListValidator runat=”server” ID=”custRadVal” ControlToValidate=”RadioButtonList1″ ErrorMessage=”At least one item in the radiobuttonlist should be checked”
EnableClientScript=”true”/>
<br />
<br />
<asp:Button ID=”Button1″ runat=”server”  Text=”Button” />
</form>

Web Page Code Behind Code

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<string> lstStr = new List<string>();
lstStr.Add(“Item 1”);
lstStr.Add(“Item 2”);
lstStr.Add(“Item 3”);
lstStr.Add(“Item 4”);
CheckBoxList1.DataSource = lstStr;
CheckBoxList1.DataBind();
RadioButtonList1.DataSource = lstStr;
RadioButtonList1.DataBind();
}
}

Very old/basic ASP.NET topic, I gave guidance on this to a beginner recently by compilation following content from net and I am sharing here the same for the benefit of other beginners …

ASP.NET Validation Controls are powerful web server controls that are used for validating user input.  These controls provides both server side and client side validation.

The client side validation features can be used to give users an improved UI experience.  By using the client side features, users will not need to wait for a full page postback to occur only to discover that they have failed to fill out form completely.  Instead, the client side features can be using to notify the user immediately (before the page is submitted) about any missing and/or invalid data.

One of the shortcomings of the validation controls under the 1.1 Framework was the inability to validate only portions of your form.  Whenever the validators were triggered, all validators on the page were checked even if they might not be related to the particular button being clicked.  With the 2.0 and above Framework versions, a new ValidationGroup property was introduced.  By setting the ValidationGroup property on a button, only those validation controls that were also set to that same ValidationGroup will be checked.

The validation can be checked on the server side with the help of the IsValid property of the validation control.  Additionally, you can use the IsValid property of the Page to check the validation result of all validation controls on the page.  Before testing the IsValid property of the validation control or the page, it is important that the validation check has already been performed through the use of the Validate method.  You can call Validate on individual controls and also on the page itself.

Validator Control Samples –

RegularExpression Validator – Client Side Validation

<form id=”form1″ runat=”server”>
<div>
Zipcode:<br />
<asp:TextBox runat=”server” id=”txt5″ />
<asp:RegularExpressionValidator runat=”server” id=”RegularExpressionValidator1″ ControlToValidate=”txt5″
errormessage=”Please enter valid zip!” ValidationGroup=”456″ ValidationExpression=”\d{5}”/>
<br /><br />
<asp:Button runat=”server” id=”txtSubmit5″ text=”Ok” ValidationGroup=”456″/>
</div></form>

Compare Validator – Client Side Validation

<form id=”form1″ runat=”server”>
<div>
Age:<br />
<asp:TextBox runat=”server” id=”txtComp” />
<asp:CompareValidator runat=”server” id=”comp1″ ControlToValidate=”txtComp”
errormessage=”Please enter 10!” Operator=”Equal” Type=”String” ValidationGroup=”345″ ValueToCompare=”10″/>
<br /><br />
<asp:Button runat=”server” id=”btnSubmit4″ text=”Ok” ValidationGroup=”345″/>
</div></form>

We can also use ControlToCompare, to directly compare ControlToValidate against other control’s value. For ex many sites will ask for 2 times entry when we create/reset password for user account and submit on page works only when both entries are same.

Required/Range Validator – Server Side Validation

Client Side Validation avoids page back to the server. For performing Validation on serverside we can add enableclientscript=”false” to the RequiredFieldValidator, RangeValidator as explained in below code

<form id=”form1″ runat=”server”>
<div>
Age:<br />
<asp:TextBox runat=”server” id=”txt3″ />
<asp:RequiredFieldValidator runat=”server” id=”reqtxt3″ controltovalidate=”txt3″
errormessage=”Please enter age!” EnableClientScript=”false” ValidationGroup=”234″/>
<asp:RangeValidator runat=”server” id=”rangetxt3″ controltovalidate=”txt3″
errormessage=”Please enter valid age!” EnableClientScript=”false”
MaximumValue=”120″ MinimumValue=”1″  Type=”Integer” ValidationGroup=”234″/>
<br /><br />
<asp:Button runat=”server” id=”btnSubmit3″ text=”Ok” onclick=”btnSubmit3_Click” ValidationGroup=”234″/>
</div></form>

Web Page Code Behind C# code

protected void btnSubmit3_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
btnSubmit3.Text = “Valid!”;
}
}

 

CustomValidator control is another validator control which is used to validate controls based on some custom logic that does not fall into the generic validations possible using the out of box other validator controls.

Following example explains how we can validate control using CustomValidator control both on client, server side.

Client Side

<form id=”form1″ runat=”server”>

<div>

<div>

Prime Number:<br />

<asp:TextBox runat=”server” id=”txt2″ />

<asp:CustomValidator runat=”server” id=”custtxt2″ controltovalidate=”txt2″

errormessage=”Please enter prime number!” ValidationGroup=”123″ ClientValidationFunction=”CheckPrime”/>

</div>

</div>

</form>

Javascript

<script language=”JavaScript”>

function CheckPrime(sender, args)

{

var iPrime = parseInt(args.Value);

var iSqrt = parseInt(Math.sqrt(iPrime));

for (var iLoop=2; iLoop<=iSqrt; iLoop++)

if (iPrime % iLoop == 0)

{

args.IsValid = false;

return;

}

args.IsValid = true;

}

</script>

ServerSide

<form id=”form2″ runat=”server”>

<div>

<div>

Prime Number:<br />

<asp:TextBox runat=”server” id=”txt1″ />

<asp:CustomValidator runat=”server” id=”custtxt1″ controltovalidate=”txt1″

errormessage=”Please enter prime number!” ValidationGroup=”234″ OnServerValidate=”PrimeNumberCheck”/>

<br /><br />

<asp:Button runat=”server” id=”btnSubmt2″ text=”Ok” onclick=”btnSubmt2_Click” ValidationGroup=”234″ />

</div>

</div>

</form>

Webpage Code Behind C# Code

public void PrimeNumberCheck(object sender, ServerValidateEventArgs args)

{

int iPrime = Convert.ToInt32(args.Value);

int iLoop = 0;

int iSqrt = Convert.ToInt32(Math.Sqrt(iPrime));

for (iLoop = 2; iLoop <= iSqrt; iLoop++)

{

if (iPrime % iLoop == 0)

{

args.IsValid = false;

return;

}

}

args.IsValid = true;

}

protected void btnSubmt2_Click(object sender, EventArgs e)

{

if (Page.IsValid)

{

btnSubmt2.Text = “Valid!”;

}

}

CustomValidator control is another validator control which is used to validate controls based on some custom logic that does not fall into the generic validations possible using the out of box other validator controls.
Following example explains how we can validate control using CustomValidator control both on client, server side.

Client Side Validation

<form id=”form1″ runat=”server”>
<div>
Prime Number:<br />
<asp:TextBox runat=”server” id=”txt2″ />
<asp:CustomValidator runat=”server” id=”custtxt2″ controltovalidate=”txt2″
errormessage=”Please enter prime number!” ValidationGroup=”123″ ClientValidationFunction=”CheckPrime”/>
</div>
</form>

Javascript

<script language=”JavaScript”>
function CheckPrime(sender, args)
{
var iPrime = parseInt(args.Value);
var iSqrt = parseInt(Math.sqrt(iPrime));
for (var iLoop=2; iLoop<=iSqrt; iLoop++)
if (iPrime % iLoop == 0)
{
args.IsValid = false;
return;
}
args.IsValid = true;
}
</script>

ServerSide Validation

<form id=”form2″ runat=”server”>
<div>
Prime Number:<br />
<asp:TextBox runat=”server” id=”txt1″ />
<asp:CustomValidator runat=”server” id=”custtxt1″ controltovalidate=”txt1″
errormessage=”Please enter prime number!” ValidationGroup=”234″ OnServerValidate=”PrimeNumberCheck” EnableClientScript=”false”/>
<br /><br />
<asp:Button runat=”server” id=”btnSubmt2″ text=”Ok” onclick=”btnSubmt2_Click” ValidationGroup=”234″ />
</div>
</form>

Webpage Code Behind C# Code

public void PrimeNumberCheck(object sender, ServerValidateEventArgs args)
{
int iPrime = Convert.ToInt32(args.Value);
int iLoop = 0;
int iSqrt = Convert.ToInt32(Math.Sqrt(iPrime));
for (iLoop = 2; iLoop <= iSqrt; iLoop++)
{
if (iPrime % iLoop == 0)
{
args.IsValid = false;
return;
}
}
args.IsValid = true;
}

protected void btnSubmt2_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
btnSubmt2.Text = “Valid!”;
}
}

EnableClientScript=”false”