how to put validation for checkbox in asp.net? - asp.net

<tr>
<td>
<asp:CheckBox ID="checkdoc" runat="server" Checked="false" />:Document
</td>
<td>
<asp:CheckBox ID="checktwocheque" runat="server" Checked="false" />:Two Cheques
</td>
<td>
<asp:CheckBox ID="checkIdprf" runat="server" Checked="false" />:ID Proof
</td>
</tr>
<tr>
<td>
<asp:CheckBox ID="checkpancrd" runat="server" Checked="false" />:PAN Card
</td>
<td>
<asp:CheckBox ID="checkAddrssprf" runat="server" Checked="false" />:Address Proof
</td>
</tr>
<tr>
<td colspan="4" align="center">
<asp:Button ID="btnfarmrecordsave" runat="server" Text="Save" OnClientClick="return Validations();" OnClick="btnfarmrecordsave_Click" />
</td>
</tr>
I have written code like this for choosing at least one checkbox. How can I write code for validation in javascript?. I want to display one message "Please select at least one checkbox" if user hasn't selected any checkbox?

Please try to implement the Validations function like this:
<script type="text/javascript">
function Validations() {
if (!(document.getElementById("<%=checkdoc.ClientID%>").checked ||
document.getElementById("<%=checktwocheque.ClientID%>").checked ||
document.getElementById("<%=checktwocheque.ClientID%>").checked ||
document.getElementById("<%=checkIdprf.ClientID%>").checked ||
document.getElementById("<%=checkpancrd.ClientID%>").checked ||
document.getElementById("<%=checkAddrssprf.ClientID%>").checked)) {
alert('You have to select atleast one choice!');
return false;
} else {
return true;
}
}
</script>

Javascript code :
if (!$(':checkbox').is(':checked')) {
alert('please, select ...');
}

<style>
.abc{
display:box
//any style you want to put
}
</style>
<script>
function Validations()
{
if ($('input.abc').not(':checked').length > 0)
{
alert("please select atleast one checkbox");
}
}
</script>
<tr>
<td>
<asp:CheckBox ID="checkdoc" runat="server" Checked="false" class="abc"/>:Document
</td>
<td>
<asp:CheckBox ID="checktwocheque" runat="server" Checked="false" class="abc"/>:Two Cheques
</td>
<td>
<asp:CheckBox ID="checkIdprf" runat="server" Checked="false" class="abc"/>:ID Proof
</td>
</tr>
<tr>
<td>
<asp:CheckBox ID="checkpancrd" runat="server" Checked="false" class="abc"/>:PAN Card
</td>
<td>
<asp:CheckBox ID="checkAddrssprf" runat="server" Checked="false" class="abc"/>:Address Proof
</td>
</tr>
<tr>
<td colspan="4" align="center">
<asp:Button ID="btnfarmrecordsave" runat="server" Text="Save" OnClientClick="return Validations();"
OnClick="btnfarmrecordsave_Click" />
</td>
</tr>

function Validations()
{
var chk = document.getElementsByTagName('input');
for (var i = 0; i < chk.length; i++)
{
if (chk[i].type == 'checkbox')
{
if (chk[i].checked) {return true}
}
}
alert("Please select atleast one checkbox");
return false;
}

Related

How to Update a Panel Out side Repeater on ItemCommand of Repeater using Update Panel in asp.net?

I have a List of Client Displayed in Repeater. I have a Details Button in Repeater which displays the Details of Client when Clicked. For Sample now just added 'ClientName' only. *When i Click on 'Details' LinkButton in Repeater it Displays the Details of Selected Row. But, this causes FullPage Post Back! Which i want to Prevent. Just i want to Update the Panel which displays the Details when row is selected from Repeater*.
In .aspx page:
<script>
function ShowPopUp() {
var listItemsRegion = document.getElementById('popup');
popup.style.display = "block";
}
function ClosePopup() {
var listItemsRegion = document.getElementById('popup');
popup.style.display = "none";
}
</script>
<asp:Repeater ID="RepDetails" runat="server" OnItemCommand="RepDetails_ItemCommand">
<HeaderTemplate>
<table class="tabl">
<tr style="background-color: #808080; color: White">
<td class="lblCenter">
<asp:Label ID="Label4" runat="server" Text="City" Font-Bold="true" CssClass="lbl"></asp:Label>
</td>
<td class="lblCenter">
<asp:Label ID="Label3" runat="server" Text="Age" Font-Bold="true" CssClass="lbl"></asp:Label>
</td>
<td class="lblCenter">
<asp:Label ID="Label1" runat="server" Text="Gender" Font-Bold="true" CssClass="lbl"></asp:Label>
</td>
<td class="lblCenter">
<asp:Label ID="Label5" runat="server" Text="Details" Font-Bold="true" CssClass="lbl"></asp:Label>
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr class="<%# Container.ItemIndex % 2 == 0 ? "rowEven" : "rowOdd" %>">
<td class="lblCenter">
<asp:Label ID="lblCity" runat="server" Text='<%#Eval("City") %>' /></td>
<td class="lblCenter">
<asp:Label ID="lblAge" runat="server" Text='<%#Eval("Age") %>' /></td>
<td class="lblCenter">
<asp:Label ID="lblGen" runat="server" Text='<%#Eval("Gender") %>' CssClass="lbl"></asp:Label>
</td>
<td class="lblCenter">
<asp:LinkButton ID="lblDetails" runat="server" CommandName="Display"
CommandArgument='<%#Eval("ID") %>'>Details</asp:LinkButton></td>
<asp:Label ID="rlblClientname" runat="server" Text='<%#Eval("Client") %>' Visible="false"></asp:Label>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<div id="popup" style="display: none">
<asp:UpdatePanel ID="UpdatePanel6" runat="server">
<ContentTemplate>
<table width="80%" align="center">
<tr>
<td> </td>
<td width="30%"> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>
<asp:Label ID="Label15" runat="server" CssClass="lbl" Text="Client Code"></asp:Label>
</td>
<td>
<asp:Label ID="lblClientName" runat="server" CssClass="lbl"></asp:Label>
</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td>
<input id="Button2" type="button" value="Close" onclick="ClosePopup();" class="but" /> </td>
</tr>
</table>
</ContentTemplate>
<%-- <Triggers>
<asp:AsyncPostBackTrigger ControlID="RepDetails" EventName="RepDetails_ItemCommand" />
</Triggers>--%>
</asp:UpdatePanel>
</div>
In Repeater Item Command:
protected void RepDetails_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Display")
{
LinkButton lblDetails = (LinkButton)e.Item.FindControl("lblDetails");
Label rlblClientname = (Label)e.Item.FindControl("rlblClientname");
if (lblDetails != null && e.CommandArgument != null)
{
string val = e.CommandArgument.ToString();
if (rlblClientname != null && rlblClientname.Text != string.Empty)
{
lblClientName.Text = rlblClientname.Text;
}
string scrpt = "ShowPopUp();";
Page.ClientScript.RegisterStartupScript(this.GetType(), "s", scrpt, true);
}
}
}
This causes Full Page Post Back Which i want to Prevent.Onclick of Repeater row the details must be displayed with AsynPostBack. When adding Trigger Event to 'popup' div then it say control could not be found
Help Appreciated!
Thanks!
You have one of two Options:
1) Uncomment this code and change EventName="RepDetails_ItemCommand" to EventName="ItemCommand"
<Triggers>
<asp:AsyncPostBackTrigger ControlID="RepDetails" EventName="ItemCommand" />
</Triggers>
2) Put the Repeater in the <ContentTemplate> of the UpdatePanel

how to validating unique entries of textbox on repeater control?

I have a repeater control rptbrand in which one textbox txtMultiBrand is there and after each repeating time when i click btnAddBrand button i want validation for unique entries in textbox, here is my aspx code
<table width="100%">
<asp:Repeater ID="rptBrand" runat="server" OnItemDataBound="rptBrandDetail_ItemDataBound">
<ItemTemplate>
<tr>
<td align="right" `enter code here`width="150">
Brand<asp:Label ID="lblBrandNum" runat="server"></asp:Label>
<span class="msgred">*</span> :
</td>
<td align="left">
<table width="100%">
<tr>
<td align="left" width="20%">
<asp:TextBox ID="txtMultiBrand" CssClass="imageSearch" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator14" runat="server" ValidationGroup="VGrpMultiSave"
ControlToValidate="txtMultiBrand" ErrorMessage="Brand Required" Display="none"
SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ValidationGroup="VGrpSave"
ControlToValidate="txtMultiBrand" ErrorMessage="Brand Required" Display="none"
SetFocusOnError="True"></asp:RequiredFieldValidator>
</td>
<td align="left">
<asp:ImageButton ID="btnDelete" runat="server" CausesValidation="false" CommandName="CmdDelete"
CommandArgument='<%# Eval("SrNo") %>' ToolTip="Delete" ImageUrl="images/b_drop.png"
OnCommand="rptBrand_Command" Width="16" Height="16" OnClientClick="javascript:return confirm('Are you sure you want to remove brand?')" />
</td>
</tr>
</table>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
<tr>
<td align="right" width="150">
</td>
<td>
<asp:Button ID="btnAddBrand" runat="server" Text="Add more" ValidationGroup="VGrpMultiSave"
OnClick="btnAddBrand_Click" />
<asp:ValidationSummary ID="ValidationSummary2" runat="server" DisplayMode="List"
ShowMessageBox="True" ShowSummary="False" ValidationGroup="VGrpMultiSave" />
</td>
</tr>
</table>
Using jQuery:
IT IS WORKING
Check the below link:
http://jsfiddle.net/NtF7h/
$(function () {
$("#<%=btnAddBrand.ClientID%>").on("click", function (event) {
var valueArray = new Array(); ;
$("input[id*='txtMultiBrand']").each(function (index) {
if ($.inArray($(this).val(), valueArray) == -1) {
valueArray[index] = $(this).val();
}
else {
alert("Duplicate Entry Found.");
event.preventDefault();
return false;
}
});
});
});

ASP.NET Wizard not moving to WizardStep index 3 in browser

I have a web feedback wizard and when I tested it in the browser, clicking the next button, it goes fine from step 1 to step 2 but then it refuses to go to step 3. Also, I tried to keep the focus on the first text box in each step, but it still isn't working right. when I click 'next' the step moves (as i said it works from Contact Info to Comments) but it scrolls up to the top of the web page and loses focus from the wizard. which is annoying.
so I have two problems: (1) my wizard only goes to two out of the four steps. (2) the wizard loses its focus.
here is what i have in my wizard control:
<asp:Wizard ID="Wizard1" runat="server" BackColor="#E6E2D8"
BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
Font-Names="Verdana" Font-Size="0.8em" ActiveStepIndex="0" Height="371px"
Width="691px" style="margin-top: 178px"
onfinishbuttonclick="Wizard1_FinishButtonClick" TabIndex="1"
onactivestepchanged="Wizard1_ActiveStepChanged"
onload="Wizard1_ActiveStepChanged" onnextbuttonclick="OnNextButtonClick"
onprerender="Wizard1_ActiveStepChanged" >
<HeaderStyle BackColor="#666666" BorderColor="#E6E2D8" BorderStyle="Solid"
BorderWidth="2px" Font-Bold="True" Font-Size="0.9em" ForeColor="White"
HorizontalAlign="Center" />
<NavigationButtonStyle BackColor="White" BorderColor="#C5BBAF"
BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="2em"
ForeColor="#1C5E55" />
<SideBarButtonStyle ForeColor="#855A21" />
<SideBarStyle BackColor="#E3D3AC" Font-Size="0.9em" VerticalAlign="Top" />
<StepStyle BackColor="#F7F6F3" BorderColor="#E6E2D8" BorderStyle="Solid"
BorderWidth="2px" VerticalAlign="Top" />
<WizardSteps>
<asp:WizardStep ID="WizardStep1" runat="server" Title="Contact Info"
StepType="Start">
<table cellpadding="10" class="style1">
<tr>
<td class="style2">
Your Name</td>
<td class="style3">
<asp:TextBox ID="nametxt" runat="server" style="margin-left: 0px"
Width="137px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="nametxt" ErrorMessage="Please Enter your name"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style5">
Email</td>
<td class="style6">
<asp:TextBox ID="emailtxt" runat="server"></asp:TextBox>
</td>
<td class="style6">
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="emailtxt" ErrorMessage="Please enter your email address"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="style5">
City</td>
<td class="style6">
<asp:TextBox ID="citytxt" runat="server"></asp:TextBox>
</td>
<td class="style6">
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
ErrorMessage="Please enter your city or town"
ValidationExpression="^[a-zA-Z0-9\s.\-]+$" ControlToValidate="citytxt"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="style5">
State</td>
<td class="style6">
<asp:TextBox ID="statebox" runat="server" MaxLength="2" Width="47px"></asp:TextBox>
</td>
<td class="style6">
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="statebox" ErrorMessage="Please enter your state"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style2">
</td>
<td class="style3" colspan="2">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" Width="163px" />
</td>
</tr>
</table>
</asp:WizardStep>
<asp:WizardStep ID="WizardStep2" runat="server" Title="Comments"
StepType="Step">
<table cellpadding="10" class="style1">
<tr>
<td class="style4">
Comments<br />(no more than 500 characters)</td>
<td>
<asp:TextBox ID="txtcomments" runat="server" Height="55px" TextMode="MultiLine"
Width="233px"></asp:TextBox>
</td>
<td>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ClientValidationFunction="ValidateComments" ControlToValidate="txtcomments"
ErrorMessage="Please enter no more than 500 characters"
OnServerValidate="CustomerValidator1"></asp:CustomValidator>
</td>
</tr>
<tr>
<td class="style4">
Rating<br />(1-5)</td>
<td>
<asp:TextBox ID="txtrating" runat="server"></asp:TextBox>
</td>
<td>
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="txtrating" ErrorMessage="Use a number between 1-5"
MaximumValue="5" MinimumValue="1"></asp:RangeValidator>
</td>
</tr>
<tr>
<td class="style4">
</td>
<td colspan="2">
<asp:ValidationSummary ID="ValidationSummary2" runat="server" Height="42px" />
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToValidate="txtcomments"></asp:CompareValidator>
</td>
</tr>
</table>
</asp:WizardStep>
<asp:WizardStep ID="WizardStep3" runat="server" Title="Summary"
StepType="Finish">
<table cellpadding="10" class="style1">
<tr>
<td class="style7">
<h3>Summary:</h3>
<br />
<asp:Label ID="nameLabel" runat="server" AssociatedControlID="namelabel"></asp:Label>
</td>
<td class="style7">
</td>
</tr>
<tr>
<td>
<asp:Label ID="EmailLabel" runat="server" AssociatedControlID="Emaillabel" ></asp:Label></td>
<td>
</td>
</tr>
<tr>
<td>
<asp:Label ID="cityLabel" runat="server" AssociatedControlID="citylabel"></asp:Label>
</td>
<td>
</td>
</tr>
<tr>
<td>
<asp:Label ID="stateLabel" runat="server" AssociatedControlID="statelabel"></asp:Label>
</td>
<td>
</td>
</tr>
<tr>
<td>
<asp:Label ID="commentslabel" runat="server" AssociatedControlID="commentslabel"></asp:Label>
</td>
<td>
</td>
</tr>
<tr>
<td>
<asp:Label ID="ratinglabel" runat="server" AssociatedControlID="txtrating"></asp:Label>
</td>
<td>
</td>
</tr>
</table>
</asp:WizardStep>
<asp:WizardStep ID="WizardStep4" runat="server" Title="Complete"
StepType="Complete">
<br />
<br />
<br />
<br />
<br />
<br />
<h3> Thank You!</h3>
</asp:WizardStep>
</WizardSteps>
</asp:Wizard>
here is what i have in the behind code: (c#)
protected void Page_Load(object sender, EventArgs e)
{
//Prevent display of sitemap on default page.
SiteMapNode node = SiteMap.CurrentNode;
if (node.ParentNode == null)
{
SiteMapPath1.Visible = false;
Wizard1.Visible = false;
}
nameLabel.Text = nametxt.Text;
EmailLabel.Text = emailtxt.Text;
cityLabel.Text = citytxt.Text;
stateLabel.Text = statebox.Text;
commentslabel.Text = txtcomments.Text;
ratinglabel.Text = txtrating.Text;
}
public void OnNextButtonClick(object sender, WizardNavigationEventArgs e)
{
this.Wizard1.Focus();
Wizard1_ActiveStepChanged(sender, e);
}
private TextBox FindFirstTextBox(Control c)
{
TextBox nothing = null;
Control results;
if ((c == null))
{
return nothing;
}
if (c.GetType() == typeof(TextBox))
{
return (TextBox)c;
}
foreach (Control child in c.Controls)
{
results = FindFirstTextBox(child);
if (results != null && (results.GetType() == typeof(TextBox)))
{
return (TextBox)results;
}
else
{
return nothing;
}
}
return nothing;
}
protected void Wizard1_ActiveStepChanged(object sender, System.EventArgs e)
{
// Set the focus to the first TextBox in the current step
WizardStepBase currentWizardStep = Wizard1.ActiveStep;
// Find the first TextBox
TextBox firstTextBox = FindFirstTextBox(currentWizardStep);
// If we found a TextBox, set the Focus
if (!(firstTextBox == null))
{
firstTextBox.Focus();
}
}
Ok that is because... you have a compare validator on your txtComments field in the 2nd step of your wizard...I would recommend to either fix it or remove it...here is the code that I am referring to (in your Wizard Step 2)
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToValidate="txtcomments"></asp:CompareValidator>
The things that are missing in the above code are:
Set "ControlToCompare" property.
Set an error message...
Update for your second problem
To keep focus on your first text box...of each tab and to keep scroll position...follow below steps...
Step 1 In your Page_Load event...add the below line of code
nametxt.Focus(); // This will make sure that your nametxt texbox has focus when your page loads for the first time
Step 2 Your FindFirstTextBox method's code can be as simple as below...so update it to the code below...
// This code is pretty much self explanatory
private TextBox FindFirstTextBox(Control c)
{
foreach (Control child in c.Controls)
{
if (child is TextBox)
return (TextBox)child;
}
//If we didn't find a TextBox
return null;
}
Step 3 Update your Wizard_ActiveStepChanged event to below...
protected void Wizard1_ActiveStepChanged(object sender, System.EventArgs e)
{
// Set the focus to the first TextBox in the current step
WizardStepBase currentWizardStep = Wizard1.ActiveStep;
// Find the first TextBox
TextBox firstTextBox = FindFirstTextBox(currentWizardStep);
// If we found a TextBox, set the Focus
if (Page.IsPostBack && firstTextBox != null)
{
firstTextBox.Focus();
}
}
In the above event code, I have changed the if statement to have an additional check for page.IsPostBack...this is because the Focus method will throw an exception...since this event is being called before your OnLoad and OnRender...Its pretty much up to you to figure out why you are calling this step so early...
Step 4 Finally, to fix your scrolling problem...you need to use an Update panel...please see below code snippet...
// Your Update Panel needs a Script Manager to work
<asp:scriptManager runat="server" ID="sm"></asp:scriptManager>
<asp:UpdatePanel runat="server" ID="panel" UpdateMode="Always">
<ContentTemplate>
// ALL YOUR CONTENT MARK UP GOES HERE
</ContentTemplate>
</asp:UpdatePanel>
This should probably fix your second problem...

How to use javascript validations for controls within ListView EditTemplate?

In Nridubai website,i am using listview EditTemplate for editing purpose. In my EditTemplate, there are controls like..
<asp:TextBox ID="txtEditEventName" runat="server"
Text='<%# Bind("event_name") %>' />
And a few more controls like dropdownlist, calender controls. Now I want to validate using javascript on these controls, but its not working.
Eg.
var eventStatus=document.getElementById("<%=txtEditEventName.ClientID%>").value;
I am not using validation controls. Please help me how to use javascript for validation on EditTemplate Controls? My EditTemplate structure is like the following:
<EditItemTemplate>
<td class="command"><asp:LinkButton ID="btnCancel" runat="server" Text="Cancel" CommandName="Cancel" />
<asp:LinkButton ID="LinkButton2" runat="server" Text="Update" CommandName="Update" />
</td>
<div class="header">View Details for '<%# Eval("event_name")%>'</div>
<tr>
<td class="edit" colspan="6" >
<div class="details">
<table class="detailview" cellpadding="0" cellspacing="0">
<tr>
<td>Event Name:</td>
<td>
<asp:TextBox ID="txtEditEventName" runat="server"
Text='<%# Bind("event_name") %>' />
</td>
<td>VenueAddress :</td>
<td>
<asp:TextBox ID="txtEditVenue" runat="server" Text='<%# Bind("venue") %>' />
</td>
</tr>
<tr>
<td>Country :</td>
<td>
<asp:DropDownList ID="lstEditCountry" runat="server"
Width="174" />
</td>
<td>Event Status:</td>
<td>
<asp:DropDownList ID="lstEditStatus" runat="server" Width="175px" >
<asp:ListItem value='0' Selected="True">-Select-</asp:ListItem>
<asp:ListItem >In-Progress</asp:ListItem>
<asp:ListItem >Completed</asp:ListItem>
<asp:ListItem >Aborted</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>Category :</td>
<td>
<asp:DropDownList ID="lstEditCategory" runat="server"
Width="174" />
</td>
</tr>
<tr>
<td>Start Date:</td>
<td>
<asp:TextBox ID="txtEditStartDate" runat="server"
Text='<%# Bind("start_date", "{0:dd/MM/yyyy}") %>' />
</td>
<td>End Date:</td>
<td>
<asp:TextBox ID="txtEditEndDate" runat="server"
Text='<%# Bind("end_date","{0:dd/MM/yyyy}") %>' />
</td>
</tr>
</table>
<div class="footer command">
<asp:LinkButton ID="LinkButton1" runat="server" Text="Close" CommandName="Cancel" />
</div>
</div>
</td>
</tr>
</EditItemTemplate>
You can access the elements on ItemDataBound and emit their ClientIDs for your JavaScript to use:
ItemDataBound:
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
StringBuilder vars= new StringBuilder();
if (ListView1.EditItem != null)
{
TextBox txtEditStartDate = ListView1.EditItem.FindControl("txtEditStartDate") as TextBox;
TextBox txtEditEndDate = ListView1.EditItem.FindControl("txtEditEndDate") as TextBox;
//example js, however I recommend passing the ClientIDs to functions
vars.Append(String.Format("var txtEditStartDate='{0}';" txtEditStartDate.ClientID);
vars.Append(String.Format("var txtEditStartDate='{0}';", txtEditEndDate.ClientID );
ClientScriptManager.RegisterStartUpScript(this.GetType(), "validationVars", vars.ToString(), true);
}
}
***Old Answer, the .NET way************
EditTemplate:
<asp:TextBox ID="txtEditEventName" runat="server"
Text='<%# Bind("event_name") %>' />
<asp:RequiredFieldValidator
id="rfvEditEventName"
ClientValidationFunction="txtEditEventNameClientValidate"
ControlToValidate="txtTitle"
runat="server"
Display="dynamic">*
</asp:RequiredFieldValidator>
JS:
function txtEditEventNameClientValidate(sender, args) {
if (args.Value == '') {
args.IsValid = false; // field is empty
//so something
}
else {
//do something
}
}
Put the validation javascript in the EditTemplate itself. This way, when it switches to edit-mode, the control will be in the context.

Validations not working

I have few text boxes which has required field validation. In the same page there is a back button and next button. When i click in the back button the validations are working, when i click on the next button validations are not working (means the form is moving to the next page)
Please help me to rectify
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="RequestorForm.aspx.vb"
Inherits="WebApplication1.RequestorForm" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Requestor Form</title>
<link rel="stylesheet" type="text/css" href="homepage2005.css">
<script language="javascript" type="text/javascript">
//Call Server Event on User id onblur()
function CallClientEvent() {
__doPostBack("txt_view1_userID_TextChanged", "");
}
function CheckValidation() {
Page_ClientValidate();
if (Page_IsValid) {
if (CheckRoleValidation()) {
if ('<%=strRoleType%>' == 'chkBx_Store_wu') {
return CheckTeamViewerDep();
}
}
else {
return false;
}
}
}
function CheckTeamViewerDep() {
var ctl = document.getElementById('chkbx_teamLeadStockRoom');
if (ctl.disabled) {
return true;
}
var tDiv = document.getElementById('chkDepGroup');
var chkitm = tDiv.getElementsByTagName("input");
for (var i = 0; i < chkitm.length; i++) {
if (chkitm[i].checked) {
return true;
}
}
var ctlvalidate = document.getElementById('span_chkDepGroup');
ctlvalidate.innerHTML = 'Please select Dep';
return false;
}
function CheckRoleValidation() {
//var cblItm = '<%=gvRoleDep%>';
var tDiv = document.getElementById('gvRoleDep');
var chkitm = tDiv.getElementsByTagName("input");
var flag = false;
var chkItemCount = 0;
for (var i = 0; i < chkitm.length; i++) {
if (chkitm[i].checked) {
chkItemCount++;
flag = true;
}
}
var ctlvalidate = document.getElementById('lbl_chkBx_store_wu');
if (!flag) {
ctlvalidate.innerHTML = 'Please select Role(s)';
return false;
}
if (chkItemCount > 5) {
ctlvalidate.innerHTML = 'Maximum of 5 Role(s) only can be checked';
return false;
}
}
function ValidateDropDown() {
Page_ClientValidate();
flag = 1;
objTOR = document.getElementById('ddl_view0_typeOfRequest');
objWUL = document.getElementById('ddl_view0_wuLevel');
if (Page_IsValid) {
//alert(objTOR.selectedIndex);
TOR = document.getElementById('span_ddl_view0_typeOfRequest');
WUL = document.getElementById('span_ddl_view0_wuLevel');
if (objTOR.selectedIndex == 0) {
//alert('Select a value:');
TOR.innerHTML = "*Please select a Type of Request";
flag = 0;
}
else
TOR.innerHTML = " ";
// if (objWUL.selectedIndex == 0) {
// WUL.innerHTML = "*Please select a W A";
// flag = 0;
// }
// else
// WUL.innerHTML = " ";
if (flag == 0)
return false;
return true;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="margin-left: 10px">
<asp:MultiView runat="server" ID="mvRequestorForm" ActiveViewIndex="0">
<asp:View runat="server" ID="view_0">
<h1 class="blue">
<asp:Label ID="lbl_viewTitle0" runat="server" Text="Label"></asp:Label>
</h1>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td class="tabRow" width="150">
<asp:Label ID="lbl_view0_firstName" runat="server" Text="Firstname "></asp:Label>
</td>
<td width="200">
<asp:TextBox ID="txt_firstName" runat="server" AutoCompleteType="FirstName"
CssClass="text_box_3" TabIndex="1"></asp:TextBox>
<asp:Label ID="Label5" runat="server" ForeColor="Red" Text="*"></asp:Label>
</td>
<td>
<asp:RequiredFieldValidator ID="Validator_FirstName" runat="server"
ControlToValidate="txt_firstName" ErrorMessage="* Required field"
ValidationGroup="Form1"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="tabRow">
<asp:Label ID="lbl_view0_surname" runat="server" Text="Surname"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtSurName" runat="server" AutoCompleteType="LastName"
CssClass="text_box_3" TabIndex="3"></asp:TextBox>
<asp:Label ID="Label6" runat="server" ForeColor="Red" Text="*"></asp:Label>
</td>
<td>
<asp:RequiredFieldValidator ID="Validator_Surname" runat="server"
ControlToValidate="txtSurName" ErrorMessage="* Required field"
ValidationGroup="Form1"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="tabRow">
<asp:Label ID="lbl_view0_ContactNum" runat="server" Text="Contact number"></asp:Label>
</td>
<td>
<asp:TextBox ID="txt_contactNum" runat="server"
AutoCompleteType="BusinessPhone" CssClass="text_box_3" TabIndex="3"></asp:TextBox>
<asp:Label ID="Label7" runat="server" ForeColor="Red" Text="*"></asp:Label>
</td>
<td>
<asp:RequiredFieldValidator ID="Validator_ContactNumber" runat="server"
ControlToValidate="txt_contactNum" ErrorMessage="* Required field"
ValidationGroup="Form1"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="txt_contactNum" ErrorMessage="Enter a numeric value"
MaximumValue="99999999999999" MinimumValue="0"></asp:RangeValidator>
</td>
</tr>
</table>
<hr class="blue" />
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td class="tabRow" width="150">
<asp:Label ID="lbl_view0_typeOfRequest" runat="server" Text="Type of request"></asp:Label>
</td>
<td width="500">
<asp:DropDownList ID="ddl_view0_typeOfRequest" runat="server"
CssClass="drop_down_t" TabIndex="4">
<asp:ListItem Value="-1">Please select...</asp:ListItem>
<asp:ListItem>New</asp:ListItem>
<asp:ListItem>Update</asp:ListItem>
<asp:ListItem>Delete</asp:ListItem>
</asp:DropDownList>
<span ID="span_ddl_view0_typeOfRequest" class="errorText"></span>
</td>
<td>
</td>
</tr>
<tr>
<td class="tabRow">
<asp:Label ID="lbl_view0_wuLevel" runat="server" Text="W A"></asp:Label>
</td>
<td>
<asp:DropDownList ID="ddl_view0_wuLevel" runat="server"
CssClass="drop_down_t" TabIndex="5">
<asp:ListItem Selected="True" Value="3">Store</asp:ListItem>
</asp:DropDownList>
<span ID="span_ddl_view0_wuLevel" class="errorText">
</span>
</td>
<td>
</td>
</tr>
<tr> <td> </td> <td></td><td> </td></tr>
</table>
<asp:Label ID="lblCaption1" runat="server"
Text="* Represents fields that needs to be filled mandatory"
Font-Size="XX-Small" ForeColor="#FF3300"></asp:Label>
<br />
<hr />
<asp:Button ID="btn_View0_Next" runat="server"
OnClientClick="return ValidateDropDown();" Text="Next"
ValidationGroup="Form1" />
<br />
</asp:View>
<asp:View runat="server" ID="view_1">
<asp:ScriptManager ID="scrMgr" runat="server">
</asp:ScriptManager>
<table>
<tr>
<td><asp:Label ID="lblException" CssClass="errorText" runat="server"></asp:Label></td>
</tr>
</table>
<h1 class="blue">
<asp:Label ID="lbl_viewTitle1" runat="server" Text="Label"></asp:Label>
</h1>
<table border="0">
<tr>
<td>
<table border="1" style="border-color:Green; border-width:thin;" width="100%">
<tr>
<td valign="top">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr id="trUserDetail" runat="server">
<td class="tabRow">
<asp:Label ID="lbl_view1_userID" runat="server"
Text="User ID "></asp:Label>
</td>
<td>
<asp:TextBox ID="txt_view1_userID" runat="server" Text="" onblur="CallClientEvent()" AutoPostBack="true" >
</asp:TextBox>
<asp:Label ID="Label1" runat="server" ForeColor="Red" Text="*"></asp:Label>
<div class="smallText" nowrap> (This would be the ID you would normally log on with.)</div>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
ControlToValidate="txt_view1_userID" ErrorMessage="* Required field"
ValidationGroup="Form2"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td width="150" class="tabRow">
<asp:Label ID="lbl_panview3_label2" runat="server" Text="St Nu "></asp:Label>
</td>
<td width="200">
<asp:TextBox ID="txt_panview3_input2" runat="server" MaxLength="4">0000</asp:TextBox>
<asp:Label ID="Label8" runat="server" ForeColor="Red" Text="*"></asp:Label>
</td>
<td>
<asp:RangeValidator ID="RangeValidator2" runat="server"
ControlToValidate="txt_panview3_input2"
ErrorMessage="Please enter a valid 4-digit St Nu " MaximumValue="999999"
MinimumValue="1" Type="Integer" ValidationGroup="Form2"></asp:RangeValidator>
</td>
</tr>
<tr>
<td colspan="3">
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server"
ControlToValidate="txt_panview3_input2" ErrorMessage="* Required field"
ValidationGroup="Form2"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="tabRow">
<asp:Label ID="lblEmployeeNumber" runat="server"
Text="Employee Number "></asp:Label>
</td>
<td>
<asp:TextBox ID="txtEmployeeNumber" runat="server">
</asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ControlToValidate="txtEmployeeNumber" ErrorMessage="* Required field"
ValidationGroup="Form2"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td width="150" class="tabRow">
<asp:Label ID="lbl_view1_firstName" runat="server" Text="Firstname "></asp:Label>
</td>
<td width="200">
<asp:TextBox ID="txt_view1_firstname" runat="server"></asp:TextBox>
<asp:Label ID="Label9" runat="server" ForeColor="Red" Text="*"></asp:Label>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txt_view1_firstname" ErrorMessage="* Required field"
ValidationGroup="Form2"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="tabRow">
<asp:Label ID="lbl_view1_surname" runat="server" Text="Surname "></asp:Label>
</td>
<td>
<asp:TextBox ID="txt_view1_surname" runat="server"></asp:TextBox>
<asp:Label ID="Label10" runat="server" ForeColor="Red" Text="*"></asp:Label>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="txt_view1_surname" ErrorMessage="* Required field"
ValidationGroup="Form2"></asp:RequiredFieldValidator>
</td>
</tr>
</table>
<asp:Label ID="lblCaption2" runat="server"
Text="* Represents fields that needs to be filled mandatory"
Font-Size="XX-Small" ForeColor="Red"></asp:Label>
<hr />
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td>
<asp:Panel ID="panelHO" runat="server">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" width="200">
<asp:Label ID="lbl_HO_wu" runat="server" CssClass="boldLabel"
Text="Role" />
</td>
<td align="left" width="200">
<asp:Label ID="lbl_panview1_label1" runat="server" CssClass="boldLabel"
Text="Dep" />
</td>
<td>
</td>
</tr>
<tr>
<td colspan="3">
</td>
</tr>
<tr>
<td align="left" valign="top">
<asp:CheckBoxList ID="chkBx_HO_wu" runat="server" />
<span id="lbl_chkBx_HO_wu" class="errorText"></span>
</td>
<td align="left" valign="top">
<asp:DropDownList ID="ddl_panview1_ddinput1" runat="server">
<asp:ListItem>Avebury</asp:ListItem>
</asp:DropDownList>
</td>
<td>
</td>
</tr>
</table>
</asp:Panel>
<asp:Panel ID="panelRegion" runat="server">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td width="30%">
<asp:Label ID="lbl_Region_wu" runat="server" CssClass="boldLabel"
Text="Role" />
</td>
<td width="30%">
<asp:Label ID="lbl_panview2_label1" runat="server" CssClass="boldLabel"
Text="Region" />
</td>
<td>
</td>
</tr>
<tr>
<td colspan="3">
</td>
</tr>
<tr>
<td valign="top">
<asp:CheckBoxList ID="chkBx_Region_wu" runat="server" />
<span id="lbl_chkBx_Region_wu" class="errorText"></span>
</td>
<td valign="top">
<asp:DropDownList ID="ddl_panview2_ddinput1" runat="server">
<asp:ListItem>Northern (NORTHERN)</asp:ListItem>
<asp:ListItem>Central (CENTRAL)</asp:ListItem>
<asp:ListItem>Southern (SOUTHERN)</asp:ListItem>
Two possibilities spring immediately to mind:
The "next" button's CausesValidation property is set to false.
The "next" button is in a different ValidationGroup to the other controls.
Make sure the CausesValidation property is set to true on the buttons that you want validation to occur when clicked.
<asp:Button CausesValidation="TRUE" runat="server" />

Resources