Show validation message depending on each other - c#

I have a following code in aspx page:
<TABLE id="tblGeneratedTo" cellspacing="0" cellpadding="0" width="100%" align="left" border="0" runat="server">
<TR>
<td width="20%" align="left"><FONT face="Verdana" size="2"><strong>To:</strong></FONT> </TD>
<td width="80%">
<asp:textbox id="txtGeneratedTo" runat="server" CssClass="ptinput" MaxLength="10" Width="90px"></asp:textbox>
<A onclick="window.open('../calPopUp.aspx?textbox=txtGeneratedTo','cal','width=230,height=190,left=400,top=200')"
href="javascript:;"> <IMG src="../images/SmallCalendar.gif" border="0"></A> <FONT class="fontbody">
(mm/dd/yyyy)</FONT>
</TD>
</TR>
<tr>
<td colspan="2" align="right">
<asp:RegularExpressionValidator ID="Regularexpressionvalidator4" runat="server" CssClass="fontbody"
Display="Dynamic" ErrorMessage="*Date should be in (mm/dd/yyyy) format."
ValidationExpression="^([\d]{1,2}/[\d]{1,2}/[\d]{4})$"
ControlToValidate="txtGeneratedTo"></asp:RegularExpressionValidator>
<asp:CompareValidator ID="CompareValidator6" runat="server" CssClass="fontbody"
Display="Dynamic" ErrorMessage="'End' date cannot fall before 'Start' date."
ControlToValidate="txtGeneratedTo" Type="Date" Operator="GreaterThanEqual"
ControlToCompare="txtGeneratedFrom"></asp:CompareValidator>
</td>
</tr>
</TABLE>
To:
(mm/dd/yyyy)
Here I have a textbox and two validation controls on it viz. regular expression and compare on actual page when I put some garbage value in textbox I see both the message at a time:
I want to see only one message at a time. Most preferably show comparevalidator message iff regularexpression validator is satisfied or else show only regularexpression validator.
How to achieve this? It will be easy if we can do something for this from MarkUp only rather than codebehind.

For this you have to use CustomValidator. The Validator
<asp:CustomValidator ID="CompareDateValidator" runat="server"
ClientValidationFunction="CompareDateValidatorClient"
ErrorMessage="Some error message" />
The ClientValidationFunction that accompanies this
function CompareDateValidatorClient(sender, args) {
var fromValue = document.getElementById('<%=txtGeneratedFrom.ClientID%>').value;
var toValue = document.getElementById('<%=txtGeneratedTo.ClientID%>').value;
var isValid = false;
if (ValidateDate(fromValue)) {
if (ValidateDate(toValue)) {
if (Date.parse(toValue) > Date.parse(fromValue)) {
isValid = true;
}
else
sender.innerHTML = "'End' date cannot fall before 'Start' date.";
}
else
sender.innerHTML = "To date should be in (mm/dd/yyyy) format.";
}
else
sender.innerHTML = "From date should be in (mm/dd/yyyy) format.";
args.IsValid = isValid;
}
function ValidateDate(str) {
var rm_date = /^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$/;
//triple check for not empty, mm/dd/yyyy format and whether the date is valid
return (str.trim() !== "" && str.match(rm_date) && !isNaN(Date.parse(str)));
}
//remedial javascript. trim function
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s*(\S*(?:\s+\S+)*)\s*$/, "$1");
};
}
// ControlToValidate property supports hooking up single element.
//The below hack hooks both txtGeneratedFrom and txtGeneratedTo to the validator
var validatorObj = document.getElementById("<%= CompareDateValidator.ClientID %>");
ValidatorHookupControlID("<%= txtGeneratedFrom.ClientID %>", validatorObj);
ValidatorHookupControlID("<%= txtGeneratedTo.ClientID %>", validatorObj);

Related

Changing Text Box to List Drop down gives "Invalid postback or callback argument" error

I have form which was built on Asp.Net platform. This form works as expected whe we enter entry as text for both Country and State and I can submit the data to the database. Now I need to change the code with the logic to have drop down for Country and State. Example: If United States is selected it shows related states and user need to select the entry from drop down and submit the form and it should save it in database. I haven't changed anything in code behind in the working code, just adding the list drop down instead of Text entry for both Country and State. I am getting error "Invalid postback or callback argument" when I click the Submit button for submission. I have included the working code with text box entry and the change I have done by replacing with the list drop down. I have also included the error detail I am getting. Looking at other postings on stackoverflow, I added enableEventValidation="false" in .aspx page, but it didn't solve the issue. Any idea how can I resolve this?
.aspx Code with Text box field: (This is working)
<tr>
<td><div align="right"><span class="style4">*</span> State:</div><asp:RequiredFieldValidator id="reqstate" ControlToValidate="state" ErrorMessage="Required Field!" runat="server" /></td>
<td><asp:TextBox runat="server" name="state" type="text" id="state" size="30" /></td>
</tr>
<tr>
<td><div align="right"><span class="style4">*</span> Country:</div><asp:RequiredFieldValidator id="reqcountry" ControlToValidate="country" ErrorMessage="Required Field!" runat="server" /></td>
<td><asp:TextBox runat="server" name="country" type="text" id="country" size="30" /></td>
</tr>
Changed .aspx Code with List Drop Down: (This is not working)
<tr>
<td><div align="right"><label id="stateLabel" style="display: none"><span class="style4">*</span> State:</label></div><asp:RequiredFieldValidator id="reqstate" ControlToValidate="state" ErrorMessage="Required Field!" runat="server" /></td>
<td><asp:ListBox name="state" id="state" style="display: none" rows="1" runat="server"></asp:ListBox></td>
</tr>
<tr>
<td><div align="right"><span class="style4">*</span> Country:</div><asp:RequiredFieldValidator id="reqcountry" ControlToValidate="country" ErrorMessage="Required Field!" runat="server" /></td>
<td>
<asp:ListBox id="country" onchange="javascript:countryChange()" rows="1" runat="server">
<asp:ListItem selected="false">Select Country</asp:ListItem>
<asp:ListItem>United States</asp:ListItem>
<asp:ListItem>Canada</asp:ListItem>
</asp:ListBox>
</td>
</tr>
<!--Country and State Change Javascript-->
<script>
function countryChange() {
var countryState = [
[
'US', [
['', 'State/Province'],
['AL', 'Alabama'],
['AK', 'Alaska'],
['AZ', 'Arizona'],
['AR', 'Arkansas'],
], ],
[
'CA', [
['', 'State/Province'],
['AB', 'Alberta'],
['BC', 'British Columbia'],
['MB', 'Manitoba'],
['NB', 'New Brunswick'],
]]
];
var countryElement = document.getElementById('countryId');
var stateElement = document.getElementById('stateId');
var stateLabelElement = document.getElementById('stateLabel');
if (countryElement && stateElement) {
var listOfState = [
['XX', 'None']
];
var currentCountry = countryElement.options[countryElement.selectedIndex].value;
for (var i = 0; i < countryState.length; i++) {
if (currentCountry == countryState[i][0]) {
listOfState = countryState[i][1];
}
}
if (listOfstate.length < 2)
{
stateElement.style.display = 'none';
stateLabelElement.style.display = 'none';
}
else
{
stateElement.style.display = 'inline';
stateLabelElement.style.display = 'inline';
}
var selectedState;
for (var i = 0; i < stateElement.length; i++) {
if (stateElement.options[i].selected === true) {
selectedState = stateElement.options[i].value;
}
}
stateElement.options.length = 0;
for (var i = 0; i < listOfState.length; i++) {
stateElement.options[i] = new Option(listOfState[i][1], listOfState[i][0]);
if (listOfState[i][0] == selectedState) {
stateElement.options[i].selected = true;
}
}
}
}
</script>
Error I am getting:
Invalid postback or callback argument. Event validation is enabled
using in configuration or <%#
Page EnableEventValidation="true" %> in a page. For security
purposes, this feature verifies that arguments to postback or callback
events originate from the server control that originally rendered
them. If the data is valid and expected, use the
ClientScriptManager.RegisterForEventValidation method in order to
register the postback or callback data for validation.

Why is e.Row.DataItem null in RowCreated function of GridView

Partial HTML source for a GridView (ID: MyGrid):
...
<tr title="Task is Past Due" style="color:#C00000;background-color:#EBE9E9;">
<td>
<input type="image" name="ctl00$ContentMain$yourTasksGV$ctl04$btnShowDepend" id="btnShowDepend" title="Click to view Dependencies" class="gvTaskDep btnShowDepend" src="es.png" alt="" />
<div id="pnlSubTasks" class="pnlSubTasks">
<div>
</div>
</div>
</td>
<td style="background-color:DarkRed;">
</td>
<td class="taskTableColumn">SOMETHING</td>
<td class="taskTableColumn">Something</td>
<td class="taskTableColumn">Something</td>
<td class="taskTableColumn">03-09-2015</td> //<asp:BoundField HeaderStyle-Width="7%" DataField="Due Date" HeaderText="Due" SortExpression="Due Date" ItemStyle-CssClass="taskTableColumn" />
<td class="taskTableColumn">Something</td>
<td class="taskTableColumn">Something</td>
<td class="taskTableColumn">Something</td>
<td class="taskTableColumn">Something</td>
<td class="taskTableColumn"> </td>
<td class="taskTableColumn"></td>
<td class="hideTag">1</td>
<td class="hideTag">155</td>
</tr>
...
When I click on the btnShowDepend image to perform some operation, it fails in the GridView RowCreated function:
if (e.Row.RowType == DataControlRowType.DataRow)
{
var k = DataBinder.Eval(e.Row.DataItem, "Due Date"); //k=null
DateTime dt;
DateTime.TryParse(DataBinder.Eval(e.Row.DataItem, "Due Date").ToString(), out dt); //e.Row.DataItem = null
if (dt < DateTime.Today)
{
//or do it for a specific cell
e.Row.Cells[1].BackColor = System.Drawing.Color.DarkRed;
}
}
Why is k null and how can I modify the code to fix it.
Please note: If it can also be done using JQuery, I would like that solution.
I would like to make the font color RED to any row where the column's Due Date is less than today's date.
I'm not an ASP.net guy, but with jQuery you could use Date.parse like this:
$('#btnShowDepend').on('click', function () {
var now = Date.now();
$('td.taskTableColumn').each(function () {
var date = Date.parse($(this).text());
// Skip invalid dates
if (isNaN(date)) return;
if (date < now) {
$(this).css({
backgroundColor: 'red'
});
}
});
});
EDIT:
To cycle through the entire table, turning each row RED if its "6th column" contains a date earlier than today, you can do this like so:
$('#btnShowDepend').on('click', function () {
var now = Date.now();
$('#myTableId tr').each(function () {
var $row = $(this);
var the6thColumn = $row.find('.my6thColumnClass');
var date = Date.parse($(the6thColumn).text());
// Skip invalid dates
if (isNaN(date)) return;
if (date < now) {
$row.css({
backgroundColor: 'red'
});
}
});
});
Assuming:
The table in question has an id of myTableId
The "6th column" cells have a class of my6thColumnClass like so: <td class="my6thColumnClass">.

How to get individual error labels to show C# asp.net

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

Text box getting cleared because of update panel

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.

Dyanamically disable validation on asp.net controls

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);

Categories