Depending upon the responses from the user when they complete a form, controls may or may not be required. All of these controls have validation attached to them. For instance, if the user hasn't lived at their address for at least 2 years, I need to validate previous address information; if not, I need to skip that validation.
I've tried disabling the validator control with jQuery and although when the validation text is 'greyed out', it still causes validation.
<script src="../../Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#ddlSpouseData').change(
function () {
var selection = $('#<%= ddlAddressData.ClientID%>').get(0).selectedIndex;
if (selection == 1) {
alert(selection);
$('#rfvAddressType').attr('disabled', 'disabled');
$('#rfvBAddress').attr('disabled', 'disabled');
}
});
});
</script>
<table id="MyTable" class="tableModule">
<tr>
<td class="tableDataBorder">
Data is not available and<br /> will be provided later.
</td>
<td class="tableDataBorder">
<asp:DropDownList ID="ddlAddressData" runat="server">
<asp:ListItem>Please Select</asp:ListItem>
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr class="hideRow">
<td class="tableDataBorder">
Identifying Document
</td>
<td class="tableDataBorder">
<asp:DropDownList ID="ddlAddressType" runat="server">
<asp:ListItem>Please Select</asp:ListItem>
<asp:ListItem>Home</asp:ListItem>
<asp:ListItem>Office</asp:ListItem>
<asp:ListItem>Other</asp:ListItem>
</asp:DropDownList>
<br />
<asp:RequiredFieldValidator ID="rfvAddressType" CssClass="regexError" ControlToValidate="ddlAddressType"
runat="server" ErrorMessage="Please select address type" Display="Dynamic"
InitialValue="Please Select"></asp:RequiredFieldValidator>
</td>
</tr>
<tr class="hideRow">
<td class="tableDataBorder">
Address
</td>
<td>
<asp:TextBox ID="txtAddress" MaxLength="50" runat="server" CssClass="StdTxtBox"></asp:TextBox><br />
<asp:RequiredFieldValidator ID="rfvBAddress" CssClass="regexError" ControlToValidate="txtAddress"
runat="server" ErrorMessage="Please enter your address" Display="Dynamic"></asp:RequiredFieldValidator>
</td>
</tr>
</table>
Instead of your RequiredFieldValidator, use a CustomValidator instead.
So for example you can change your 'rfvAddressType' requiredfieldvalidator as follows:
<asp:CustomValidator runat="server"
id="valAddressType"
controltovalidate="ddlAddressType"
onservervalidate="cusCustom_ServerValidate"
errormessage="Please select address type" />
Then on the server code:
protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
if (ddlAddressType.SelectedItem.Value == "1")
e.IsValid = false; // or do any additional validation checks here!
else
e.IsValid = true;
}
More details here:
http://asp.net-tutorials.com/validation/custom-validator/
https://web.archive.org/web/20211020145934/https://www.4guysfromrolla.com/articles/073102-1.aspx
Try disabling or enabling validators on the run to achieve your desired functionality. You can try this code. I haven't tested it.
//Syntax:
ValidatorEnable(ValidatorContronName,Boolean);
//Explanation:ValidatorContronName - This is ClientID of the Validation control.
Boolean - true(Enable) / false(Disable)
//Example:
ValidatorEnable(document.getElementById('<%=rfvAddressType.ClientID%>'), false);
Related
I am having an issue with trying to enable or disable a requiredfieldvalidator using a checkbox. Obviously, when the checkbox is checked I want it to be enabled and unchecked to be disabled. When the checkbox is checked it also opens up a FileUpload so obviously I would want that to register if there is not file chosen. Here is some of my code.
HTML:
<tr>
<td>
<asp:CheckBox ID="chkExecLAF" Text="Executed LAF" runat="server" OnCheckedChanged="chkExecLAF_CheckedChanged" />
</td>
<td id="tblExecLAF">
<asp:FileUpload ID="FileUpload1" runat="server" CssClass="FileUpload1" />
<asp:RequiredFieldValidator ID="rfvExecLAF" ControlToValidate="FileUpload1" ErrorMessage="*Required" ForeColor="Red" runat="server" />
</td>
<td>
<asp:CheckBox ID="chkDatedLeaseAbstract" Text="Dated Lease Abstract" runat="server" />
</td>
<td>
<asp:FileUpload ID="FileUpload2" runat="server" CssClass="FileUpload2" />
</td>
</tr>
Code Behind:
protected void chkExecLAF_CheckedChanged(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
rfvExecLAF.Enabled = false;
}
else
{
rfvExecLAF.Enabled = true;
}
}
jquery:
<script type="text/javascript">
$(function () {
$('.FileUpload1').attr('disabled', true);
$('.rfvExecLAF').attr('disabled', true);
$('.rfvExecLAF').hide();
$('.FileUpload1').hide();
$('#<%=chkExecLAF.ClientID %>').click(function () {
if ($(this).is(':checked')) {
$('.FileUpload1').removeAttr('disabled');
$('.rfvExecLAF').removeAttr('disabled');
$('.rfvExecLAF').show();
$('.FileUpload1').show();
} else {
$('.FileUpload1').attr('disabled', true);
$('.rfvExecLAF').attr('disabled', true);
$('.rfvExecLAF').hide();
$('.FileUpload1').hide();
}
});
});
</script>
Have you tried adding a breakpoint to your codebehind and see if that breakpoint is hit on CheckedChanged?
If it doesn't hit then you may want to add AutoPostBack = 'true' to your chkExecLAF
I am working on a contact page and would like some help please on how to display error labels at individual times when the textboxes are empty. I have used 3 textboxes. I am a new student in C# asp.net. I really appreciate your time and help. Thanks!
//if no or incorrect entries are entered panel with red message using a label appears to remind the user of
//if name, email, enquiry is blank error labels show up
if (nameContactUsTextBox.Text == "" && emailContactUsTextBox.Text == "" && enquiryContactUsTextBox.Text == "")
{
nameErrorLabel.Visible = true;
emailErrorLabel.Visible = true;
equiryErrorLabel.Visible = true;
}
if (nameContactUsTextBox.Text != "" && emailContactUsTextBox.Text == "" && enquiryContactUsTextBox.Text == "")
{
emailErrorLabel.Visible = true;
equiryErrorLabel.Visible = true;
}
if (nameContactUsTextBox.Text == "" && emailContactUsTextBox.Text != "" && enquiryContactUsTextBox.Text == "")
{
nameErrorLabel.Visible = true;
equiryErrorLabel.Visible = true;
}
if (nameContactUsTextBox.Text == "" && emailContactUsTextBox.Text == "" && enquiryContactUsTextBox.Text != "")
{
nameErrorLabel.Visible = true;
emailErrorLabel.Visible = true;
}
aspx file
<p>
<table style="width: 100%;">
<tr>
<td class="boring">Name</td>
<td class="auto-style1">
<asp:TextBox ID="nameContactUsTextBox" runat="server" CssClass="boring" ToolTip="Enter Name" Width="441px"></asp:TextBox>
<asp:Label ID="nameErrorLabel" runat="server" CssClass="redalert" Text="*complete name" Visible="False"></asp:Label>
</td>
</tr>
<tr>
<td class="boring">E-Mail</td>
<td>
<asp:TextBox ID="emailContactUsTextBox" runat="server" CssClass="boring" ToolTip="Enter Email" Width="443px"></asp:TextBox>
<asp:Label ID="emailErrorLabel" runat="server" CssClass="redalert" Text="*complete email" Visible="False"></asp:Label>
</td>
</tr>
<tr>
<td class="boring">Enquiry</td>
<td class="auto-style5">
<asp:TextBox ID="enquiryContactUsTextBox" runat="server" CssClass="classic" Height="158px" ToolTip="Enter Enquiry" Width="441px"></asp:TextBox>
<asp:Label ID="equiryErrorLabel" runat="server" CssClass="redalert" Text="*complete enquiry" Visible="False"></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style5"></td>
<td class="auto-style2"></td>
</tr>
<tr>
<td class="smallheader" colspan="2"> </td>
</tr>
<tr>
<td class="auto-style5"> </td>
<td class="auto-style2"> </td>
</tr>
<tr>
<td class="auto-style5" colspan="2">
<asp:Button ID="sendButton" runat="server" CssClass="smallheader" OnClick="sendButton_Click" Text="Send" ToolTip="Sending to NeoMan!" Width="200px" />
<asp:Button ID="homeButton" runat="server" CssClass="smallheader" OnClick="homeButton_Click" Text="Home" ToolTip="Continue Shopping With NeoMan" Width="200px" />
<asp:Button ID="resetButton" runat="server" CssClass="smallheader" OnClick="resetButton_Click" Text="Reset Form" ToolTip="Clear Form" Width="200px" />
</td>
</tr>
<tr>
You could use the TextChangedEvent like so:
protected void nameContactUsTextBox_TextChanged(object sender, EventArgs e)
{
nameErrorLabel.Visible = nameContactUsTextBox.Text == "";
}
And add the textchanged-event for each of the textboxes.
Microsoft already have buil ib validators that you can use to do this sort of task. To make sure that the field is not empty use the Required Field validator see this example on the w3c school website http://www.w3schools.com/aspnet/showaspx.asp?filename=demo_reqfieldvalidator.
For more complex validation use can use the regular expression validator. check the msdn website(http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.regularexpressionvalidator%28v=vs.110%29.aspx) for this it quite straight forward.
you can also investigate the JQuery validator it is quite flexible to do more interesting validation.
That's because you need to hide labels when they're not supposed to be shown, not only hide it. Change ifs to if-elses and add a summary else condition
else
{
nameErrorLabel.Visible = false;
emailErrorLabel.Visible = false;
equiryErrorLabel.Visible = false;
}
You should use the
placeholder
property of the textbox to display the type of value you need entered and examine those answers with jquery either after the boxes lose focus or upon a click of a button. If you need some sample code let me know
I've have one table, in that table within one I've one and within that , I've update panel whose update mode is set to conditional. Within this update panel I've another table. The table contains 3 text boxes as: old password, new password and confirm password. On the textChanged event of the old password I am checking the user entered value with the value in db. But when the function completes its execution all the 3 text boxes looses its values regardless of whether I update the update panel or not. I don't know why it clears text boxes. I want to prevent text boxes from getting cleared. I tried to get the text box text in string variable and again assign it to text boxes (both in text box text changed event and in page load event under isPostBack condition) but its too, not working.
asp code:
.
.
.
<tr>
<td colspan="3">
<div>
<asp:UpdatePanel ID="updPnlChngPwd" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<table style="width:100%">
<tr>
<td>
Old Password
</td>
<td>:</td>
<td>
<asp:TextBox ID="txtOldPwd" runat="server" Height="21px" MaxLength="50" TextMode="Password" Width="60%" ontextchanged="txtOldPwd_TextChanged"
AutoPostBack="True"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<asp:Label ID="lblWrongOldPwd" runat="server" Text="Wrong Old Password" ForeColor="Red" Visible="False"></asp:Label>
</td>
</tr>
<tr>
<td>
Password
</td>
<td>:</td>
<td></td>
</tr>
<tr>
<td></td>
<td>:</td>
<td>
<asp:TextBox ID="txtSuppRePwd" runat="server" Height="21px" MaxLength="50" TextMode="Password" Width="60%"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnUpdPwd" runat="server" Text="Change Password" onclick="btnUpdPwd_Click"/></td>
<td>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<td>
</tr>
.
.
.
C# code for tetxt box textChanged event:
protected void txtOldPwd_TextChanged(object sender, EventArgs e)
{
DataTable dtOldPwd = Obj.DBAccess("select Pwd from Customer where Cust_Id = " + Convert.ToInt32(Session["SuppID"]) + " and Supp_Pwd = '" + txtOldPwd.Text + "'");
if (dtOldPwd.Rows.Count == 1)
{
lblWrongOldPwd.Visible = false;
}
else
{
lblWrongOldPwd.Visible = true;
updPnlChngPwd.Update();
}
}
Now I am not able to understand what exactly wrong I am doing, does having update panel inside the table causing problem?
<td>
<asp:TextBox ID="txtSuppRePwd" runat="server" Height="21px" MaxLength="50" TextMode="Password" Width="60%"></asp:TextBox>
</td>
You have TextMode set to password which will not save your textbox value .
However you will get your textbox value as string on textchange event
protected void txtbx_TextChanged(object sender, EventArgs e)
{
string txtValue = txtbx.Text;
ViewState["xyz"]= txtValue;
}
and you have to save this value in ViewState to use it for btnClick event .
OR
You can also set textbox attribute at Page_Load event which is a very bad practice to do like this
protected void Page_Load(object sender, EventArgs e)
{
txtbx.Attributes.Add("value", txtbx.Text);
TextBox with TextMode="Password" will be cleared after postback or partial postback. This is the default behavior of the password textbox so submit all the data at a time and do the validation in your code.
Alternatively, You can store password in in viewstate or session and restore after postback.
I have a sales simulator written in C#. I did not write this however I am currently modifying it to suit different requirements.
It basically displays a list of products from a database, and has a textbox for each product where you can enter in the quantity sold. The quantity sold is calculated based on it's price in the database.
Now it's all working fine, however there is one SMALL issue. When "Buy" is clicked, it returns me back to the list of products which IS correct, however the quantity I have entered for the previous product remains.
I would like to know how to restore the text boxes to their default value when the after the data is submitted to the database.
I always thought the way to do this would be in the .cs code behind file
txtQuantity.Text = "";
However, for some odd reason, txtQuantity will not show up.
Can anyone think of anything I am doing wrong? Here is a snippet of code from the aspx file.
<form id="form1" runat="server">
Date:
<asp:TextBox ID="txtDate" runat="server" />
Retailer:
<asp:DropDownList ID="dlStore" runat="server"
onselectedindexchanged="dlStore_SelectedIndexChanged" />
<asp:ListView ID="lbProducts" runat="server">
<LayoutTemplate>
<layouttemplate>
<table border="1" cellpadding="1" style="width:800px">
<tr style="background-color:#E5E5FE">
<th>ID</th>
<th>ProductCode</th>
<th>Product Title</th>
<th>RRP $</th>
<th>Quantity</th>
<th>Sale Price $</th>
</tr>
<tr id="itemPlaceholder" runat="server"></tr>
</table>
</layouttemplate>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td style="width: 50px;">
<%#Eval("ProductID") %>
</td>
<td>
<%#Eval("ProductCode") %>
</td>
<td>
<%#Eval("ProductTitle") %>
</td>
<td>
<%#Eval("USListPrice") %>
</td>
<td style="width: 50px;">
<asp:TextBox ID="txtQuantity" runat="server" Text="0" />
</td>
<td style="width: 50px;">
<asp:TextBox ID="txtSalePrice" runat="server" Text="0.00" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:Button ID="btnBuy" Text="Buy These Items" runat="server" OnClick="btnBuy_Click" />
<asp:Button ID="btnClear" Text="Clear Existing Sales" runat="server"
onclick="btnClear_Click" />
</form>
There's a lot going on in the code behind file and I wouldn't expect anyone to go through it, but how I collect the data from txtQuantity is done with the following line of code:
Int32 quantity = Int32.Parse(((TextBox)item.FindControl("txtQuantity")).Text);
So what I want to be able to do is set this textbox either to be empty, or back to zero.
Any help is appreciated, thanks.
Because that txtQuantity control is within a ListView, there could be any number of instances of that control generated. So you can't access all of them through a single variable.
You will need to look through all controls within that ListView (and several levels deep) to find all your txtQuantity controls.
The same of course for the txtSalePrice control.
EDIT
You could find those textboxes with code like (untested)
public IEnumerable<TextBox> FindTextBoxes(Control parent)
{
if (parent == null) yield break;
foreach (Control child in parent.Controls)
{
TextBox tb = child as TextBox;
if (tb != null)
yield return tb; // found one!
else
foreach(TextBox tb in FindTextBoxes(child))
yield return tb; // found it deeper
}
}
and call it like:
foreach(TextBox tb in FindTextBoxes(lbProducts)
{
if (tb.Name == "txtQuantity")
{
// found a quantity
}
else if (tb.Name == "txtSalePrice")
{
// found the salesprice
}
}
I have a repeater inside which i put a Checkbox and above rapeater there is a HTML checkbox which is used to Check/Uncheck a Checkbox which is inside repeater using client side javascript.
Here is my Code:
JavaScript for Check/Uncheck:
<script type="text/javascript">
function selectAll() {
for (i = 0; i < document.all.length; i++) {
alert("Working");
if (document.all[i].type == 'checkbox') {
if (document.getElementById(cbSelectAll).Checked = true) {
//document.all[i].Checked = false;
} else {
document.all[i].Checked = true;
}
}
}
}
</script>
HTML Code for Repeater:
<div id="hdPropertyList" runat="server">
<table border="0" cellpadding="0" cellspacing="0" class="navigation" width="100%">
<tr>
<td>
<input type="checkbox" id="cbSelectAll" onchange="selectAll()" />
<asp:Button runat="server" ID="btnContactAll" Text="Contact All" />
</td>
<td id="tdOrderBy" runat="server">
</td>
<td>
<asp:Label ID="lblPage" runat="server" CssClass="pageList"></asp:Label>
</td>
</tr>
</table>
</div>
<div class="boxleft SearchFeaturedlist" style="display: none">
<h2>
Featured Properties</h2>
</div>
<asp:Repeater ID="rptPropertyList" runat="server" EnableViewState="false" OnItemDataBound="rptPropertyList_ItemDataBound"
OnLoad="rptPropertyList_Load">
<ItemTemplate>
<table id="propertyTable" runat="server" enableviewstate="false">
<tr id="tbrLabel" runat="server" enableviewstate="false">
<td id="tbcLabel" colspan="3" runat="server" enableviewstate="false">
</td>
</tr>
<tr id="tbrTitle" runat="server" enableviewstate="false">
<td id="tbcTitle" runat="server" enableviewstate="false">
<asp:CheckBox ID="ChkSelect" runat="server" /><span id="spnSelect" runat="server"></span>
</td>
</tr>
</table>
<div id="divAds" runat="server" visible="false" enableviewstate="false" style="width: 100%;
overflow: hidden">
</div>
</ItemTemplate>
</asp:Repeater>
Please help me in this regards.
Thanks in Advance.
The ID of the repeater will be available through it's ClientID property.
Really, you want to be asking whether you need this at all. Why not place the repeater inside a named div, and then simply find all input elements that have a type of checkbox that reside within it ( getElementsByTagName would help here ).
With a decent js addon library, like mootools or jQuery, you'll be able to use CSS selectors, which will make your task even easier.
Here's mootools example :-
function selectAllOrNone()
{
var myNewValue = $('selectall').innerText == "All" ? "None" : "All";
var myCheckers = $$('input[type=checkbox]');
$('selectall').innerText = myNewValue;
myCheckers.each(
function(e) {
e.checked = (myNewValue == "None");
}
);
}
I got the answer using Jquery. I used only the HTML checkbox to Check Uncheck all the checkbox on my Asp.net page.
<script type="text/javascript">
$(document).ready(function() {
$('td.title_listing :checkbox').change(function() {
$('#cbSelectAll').attr('checked', false);
});
});
function CotactSelected() {
var n = $("td.title_listing input:checked");
alert(n.length);
var s = "";
n.each(function() {
s += $(this).val() + ",";
});
window.location = "/D_ContactSeller.aspx?property=" + s;
alert(s);
}
Thanks to "Paul Alan Tylor" for your guidance.