ASp:NET How to perform Date Difference validation on client side? - javascript

I need to validate the input so the difference between Date1 and Date2 no more then 30 days.
I'm trying to use custom validation in asp.net, but not sure if in my case it would be the correct choice.
I have the following html:
.
.
.
<tr>
<td>
<asp:Label ID="lblFileDate" runat="server">File Date: from</asp:Label>
</td>
<td>
<asp:TextBox ID="txtDateFrom" runat="server" CssClass="datepicker1"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvDateFrom" runat="server" ControlToValidate="txtDateFrom" ForeColor="Red" ErrorMessage="Date From is Required" ValidationGroup="vgForm" >*</asp:RequiredFieldValidator>
</td>
<td style="padding-left:40px; text-align:right;">
<asp:Label ID="lblDateTo" runat="server" >to:</asp:Label>
</td>
<td width="165">
<asp:TextBox ID="txtDateTo" runat="server" colspan="2" CssClass="datepicker2"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvDateTo" runat="server" ControlToValidate="txtDateTo" ForeColor="Red" ErrorMessage="Date To is Required" ValidationGroup="vgForm" >*</asp:RequiredFieldValidator>
<asp:CustomValidator ID="cstDateValidation" runat="server" ErrorMessage="Date difference should not be more then 30 days" ClientValidationFunction="ValidateDateDiff"></asp:CustomValidator>
</td>
</tr>
<tr>
<td style="text-align: right;" colspan="4">
<asp:Button id="btnSearch" Text="Search" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" runat="server"
CausesValidation="true" CommandName="Search" OnCommand="btnSearch_Click" OnClientClick="return ValidateFields()" />
</td>
</tr>
.
.
.
<div id="errorDisplay">
<asp:ValidationSummary ID="vSum" runat="server" ShowSummary="true" ValidationGroup="vgForm"></asp:ValidationSummary>
</div>
This is my javascript:
function ValidateFields() {
var isValid = false;
isValid = Page_ClientValidate('vgForm');
if (!isValid) {
$('#errorDisplay').dialog({
title: "Validation Error",
modal: true,
resizable: false,
width: 250,
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
return false;
}
return true;
}
function ValidateDateDiff(sender, args) {
var dateFrom = $('#cphBody_Cnt_txtDateFrom').val();
var dateTo = $('#cphBody_Cnt_txtDateTo').val();
var diff = dateFrom - dateTo;
if (diff > 30) {
args.IsValid = false;
}
}
What is the best way to do something like that?

Related

Asp. Net Get Confirmation Popup Based on Condition and Get its Value at Code Behind

In the below code there is a radiobuttonlist control and Multiline textbox. On button click I would need to check whether textbox query should contain any WHERE clause. If yes then will get executed directly, but if not then should get confirmation box. If clicked on "Ok" then should get proceed but if clicked on "Cancel" then process get terminated there itself.
In my case confirmation box is not popping up and how to get it's value at code behind?
For this I would have followed an article as
https://www.aspsnippets.com/Articles/Server-Side-Code-Behind-Yes-No-Confirmation-Message-Box-in-ASPNet.aspx
below is my code
HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function alertmsg(m) {
alert(m);
}
function alertmsgwithYesNo(m) {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm(m)) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<table width="100%">
<tr>
<td align="center" valign="top">
<table cellspacing="5">
<tr>
<td align="left" valign="top"><strong>Options : </strong>
<asp:RadioButtonList ID="RadioButtonListoptions" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Value="1">Execute Directly</asp:ListItem>
<asp:ListItem Value="2">Display In Gridview</asp:ListItem>
<asp:ListItem Value="3">Display On Label</asp:ListItem>
</asp:RadioButtonList> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Select option" ControlToValidate="RadioButtonListoptions" Display="Dynamic" SetFocusOnError="true" ForeColor="Red"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td align="left" valign="top">
<asp:TextBox ID="TextBoxQuery" runat="server" TextMode="MultiLine" Height="400px" Width="800px" placeholder="Enter query..." Font-Size="Large" Text="" Style="padding: 5px;"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Enter your query" ControlToValidate="TextBoxQuery" Display="Dynamic" SetFocusOnError="true" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="center">
<asp:Button ID="ButtonSubmitQuery" runat="server" Text="Submit" Width="200px" Height="30px" OnClick="ButtonSubmitQuery_Click" /></td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="center" valign="top">
<asp:Label ID="LabelShowData" runat="server" Text="Label Here"></asp:Label>
<asp:GridView ID="GridViewData" runat="server" AutoGenerateColumns="true" EmptyDataText="No record found."></asp:GridView>
<asp:SqlDataSource ID="SqlDataSourceData" runat="server"></asp:SqlDataSource>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
C#:
protected void ButtonSubmitQuery_Click(object sender, EventArgs e)
{
if (RadioButtonListoptions.SelectedIndex != -1)
{
if (Convert.ToInt32(RadioButtonListoptions.SelectedItem.Value.ToString()) == 1)
{
if (!TextBoxQuery.Text.ToString().Contains("Where"))
{
ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "message", "alertmsgwithYesNo('Entered query did not have WHERE condition.');", false);
//ClientScript.RegisterClientScriptBlock(this.GetType(), "UpdateTime", "alertmsgwithYesNo('Query did not have WHERE Condition. Do you want to run it without Where Con');", true);
string confirmValue = Request.Form["confirm_value"];
Label1.Text = confirmValue;
return;
}
using (SqlConnection conn = new SqlConnection(vali.constr))
{
try
{
using (SqlCommand cmdsql = new SqlCommand(TextBoxQuery.Text.Trim()))
{
conn.Open();
int count = cmdsql.ExecuteNonQuery();
if (count > 0)
{
ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "message", "alertmsg('Select Option');", false);
}
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
}
}
else
{
ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "message", "alertmsg('Select Option');", false);
return;
}
}

How to disable TextBox if it not empty By JavaScript on page Load

I have an asp.net page that contain some textbox in ListView
I want to disable textbox that have some text by asp.net ItemDataBound ListView Event or Javascript code
How can i do that?
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" >
<ItemTemplate>
<tr class="xl68" height="29" style='mso-height-source: userset; height: 21.75pt'>
<td > <asp:Label ID="lblID" runat="server" Visible="false" Text='<%# Eval("ID") %>'></asp:Label></td>
<td class="xl66" style='border-top: none'><%# Container.DataItemIndex + 1 %> </td>
<td class="xl69" width="351" style='border-top: none; border-left: none; width: 263pt'> <%# Eval("Name") %></td>
<td><asp:TextBox runat="server" MaxLength="2" Text='<%# Bind("C1") %>' ID="txb1" ></asp:TextBox></td>
<td><asp:TextBox runat="server" MaxLength="2" Text='<%# Bind("C2") %>' ID="txb2" ></asp:TextBox></td>
<td><asp:TextBox runat="server" MaxLength="2" Text='<%# Bind("C3") %>' ID="txb3" ></asp:TextBox></td>
<td><asp:TextBox runat="server" MaxLength="2" Text='<%# Bind("C4") %>' ID="txb4" ></asp:TextBox></td>
<td><asp:TextBox runat="server" MaxLength="2" Text='<%# Bind("C5") %>' ID="txb5" ></asp:TextBox></td>
<td class="xl67"> </td>
</tr>
</ItemTemplate>
</asp:ListView>
add the CssClass property with every TextBox control like this
<asp:TextBox runat="server" MaxLength="2" ID="txb1" CssClass="myCss" ></asp:TextBox>
add the Js function in aspx
function DisableInput(){
var inputs = $('input.myCss[type="text"]');
inputs.each(function( index )
{
if( $( this ).text() !='')
{
$( this ).attr('disabled',true);
}
});
}
On you Page_Load event add this code
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:DisableInput(); ", true);
On you Page_Load event add this code
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:disablewithText(); ", true);
In that javaScript function you can iterate through all the textboxes and check for having value and accordingly you can set disable attribute.
I Solved it in CodeBehind by this code in Page_Load Event
foreach (ListViewItem row in ListView1.Items)
{
foreach (Control txt in row.Controls)
{
if (txt is TextBox)
{
if (((TextBox)txt).Text != "")
((TextBox)txt).Enabled = false;
}
}
}

Whats wrong with my jQuery Code for RadioButtonList

I have a UserControl "Day" that is repeated 5 times in another UserControl for 5 weekdays in a week that means each day 1 UserControl. And in this UserControl has RadioButtonList rdlAmountSlot is repeated 4 times with the below data
rdlAmountSlot_0 - Amount1 --- (1 - 100)
rdlAmountSlot_1 - Amount2 --- (100 - 1000)
rdlAmountSlot_2 - Amount3 --- (1000 - 10000)
rdlAmountSlot_3 - Amount4 --- (10000 - 100000)
I used the below code for confirmation from the user
$(document).ready(function(){
$("[id^='rdlAmountSlot_'][type='radio']").change(function () {
var radioBtnId = this.id;
var $this = $(this);
radconfirm('Are you sure you want to select this slot?', function(arg){
if (arg == true) {
$find('<%= FindControl("txtAmount").ClientID %>').set_value("");
}
else {
$this.siblings('input').prop('checked',true);
var rdlAmountSlot = document.getElementById(radioBtnId);
rdlAmountSlot.checked = false;
$this.prop('checked', false);
}
}, 300, 100,"");
});
});
The above code is throwing confirmation box for 5 times. What could be the reason and how to resolve it?
UPDATE
Below is my markup code for each day
<asp:UpdatePanel runat="server" ID="pnlUpdate" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="pnlDayView" runat="server">
<asp:RadioButtonList ID="rdlAmountSlot" CssClass="radio1" runat="server" ClientIDMode="Static">
</asp:RadioButtonList>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Below is the markup for 5 days
<table>
<tr>
<td>
<asp:Panel ID="pnlMonday" runat="server" >
<uc1:My ID="MyMonday" runat="server" />
</asp:Panel>
</td>
<td>
<asp:Panel ID="pnlTuesday" runat="server" >
<uc1:My ID="MyTuesday" runat="server" />
</asp:Panel>
</td>
<td>
<asp:Panel ID="pnlWednesday" runat="server" >
<uc1:My ID="MyWednesday" runat="server" />
</asp:Panel>
</td>
<td>
<asp:Panel ID="pnlThursday" runat="server" >
<uc1:My ID="MyThursday" runat="server" />
</asp:Panel>
</td>
<td>
<asp:Panel ID="pnlFriday" runat="server" >
<uc1:My ID="MyFriday" runat="server" />
</asp:Panel>
</td>
</tr>
<table>
This is the code similar to rdlAmountSlot
<table id="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability" class="radio1" border="0" style="color: #004B59; font-size: 11px; font-family: Arial, Sans-serif; text-align: justify">
<tr>
<td><span disabled="disabled"><input id="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability_0" type="radio" name="ctl00$ContentPlaceHolder1$MyAvailability$MyAvailabilityMonday$rdlAvailability" value="AVL01" disabled="disabled" /><label for="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability_0">Slot 0</label></span></td>
</tr><tr>
<td><input id="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability_1" type="radio" name="ctl00$ContentPlaceHolder1$MyAvailability$MyAvailabilityMonday$rdlAvailability" value="AVL02" /><label for="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability_1">Slot 1</label></td>
</tr><tr>
<td><input id="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability_2" type="radio" name="ctl00$ContentPlaceHolder1$MyAvailability$MyAvailabilityMonday$rdlAvailability" value="AVL03" /><label for="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability_2">Slot 2</label></td>
</tr><tr>
<td><input id="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability_3" type="radio" name="ctl00$ContentPlaceHolder1$MyAvailability$MyAvailabilityMonday$rdlAvailability" value="AVL04" checked="checked" /><label for="ctl00_ContentPlaceHolder1_MyAvailability_MyAvailabilityMonday_rdlAvailability_3">Slot 3</label></td>
</tr>
</table>
May be if you try with each it would work.
$(document).ready(function(){
$("[id^='rdlAmountSlot_'][type='radio']").each(function () {
$(this).change(function(){
var radioBtnId = this.id;
var $this = $(this);
radconfirm('Are you sure you want to select this slot?', function(arg){
if (arg == true) {
$find('<%= FindControl("txtAmount").ClientID %>').set_value("");
}
else {
$this.siblings('input').prop('checked',true);
var rdlAmountSlot = document.getElementById(radioBtnId);
rdlAmountSlot.checked = false;
$this.prop('checked', false);
}
}, 300, 100,"");
})
});
});

document.getelementbyId Always returning null

I am having trouble setting panel visibility
but on change JavaScript returning null reference exception.
JavaScript runtime error: Unable to get property 'setAttribute' of undefined or null reference
I want to make panel TrMarketingDetails visible based on a radio button (RbMarketing) change.
JavaScript
function trVisible(val) {
var selected = $("#" + val.id + " input:radio:checked").val();
if (selected == "1") {
document.getElementById('<%=TrMarketingDetails.ClientID %>').setAttribute("style", "visibility: visible");
document.getElementById('<%= hfdMarket.ClientID %>').value = 'Y';
}
else if (selected == "2") {
document.getElementById('<%=TrMarketingDetails.ClientID %>').setAttribute("style", "visibility: hidden");
}
}
AXPX Code
<tr>
<td style="font-weight: bold" align="left" class="style4">
Marketing facilities available
</td>
<td style="font-weight: bold" class="style23">
<asp:RadioButtonList ID="RbMarketing" runat="server" DataTextField="Yes" onchange="trVisible(this);"
RepeatDirection="Horizontal">
<asp:ListItem Text="Yes" Value="1"></asp:ListItem>
<asp:ListItem Text="No" Value="2"></asp:ListItem>
</asp:RadioButtonList>
<asp:HiddenField ID="hfdMarket" runat="server" />
<%--OnSelectedIndexChanged="RbMarketing_SelectedIndexChanged" AutoPostBack="True"--%>
</td>
</tr>
<asp:Panel ID="TrMarketingDetails" runat="server" Style="visibility: hidden" EnableViewState="true">
<tr>
<%--visible="false"--%>
<td runat="server" style="border: none;" class="style7" align="left">
Details :
</td>
<td runat="server" style="border: none;" class="style26" align="left">
<asp:TextBox ID="TextMarketingDetails" runat="server" CssClass="textboxCss" autocomplete="off"
MaxLength="100" Enabled="True" ondrop="return false;" Width="300px" TextMode="MultiLine"></asp:TextBox>
<asp:RequiredFieldValidator ID="Requiredfieldvalidator49" runat="server" Display="None"
ControlToValidate="TextMarketingDetails" ValidationGroup="grp1" ForeColor="#F00000"
SetFocusOnError="true" ErrorMessage="Please enter Marketing details" Enabled="false"></asp:RequiredFieldValidator>
<asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender3" runat="server" PopupPosition="Right"
TargetControlID="Requiredfieldvalidator49">
</asp:ValidatorCalloutExtender>
</td>
</tr>
</asp:Panel>
W3C link for style.visibility
document.getElementById("controlid").style.visibility = "hidden"
you just change like
function trVisible(val) {
var selected = $("#" + val.id + " input:radio:checked").val();
if (selected == "1") {
document.getElementById('<%=TrMarketingDetails.ClientID %>').style.visibility = "visible";
document.getElementById('<%= hfdMarket.ClientID %>').value = 'Y';
}
else if (selected == "2") {
document.getElementById('<%=TrMarketingDetails.ClientID %>').style.visibility = "hidden";
}
}
You are already use jquery syntax in your code, then good to do this via jquery syntax like
$('#<%=TrMarketingDetails.ClientID %>').show();
$('#<%=TrMarketingDetails.ClientID %>').hide();
Check this link with same question

TextBox does not get it's value from code behind after postback

please consider this code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<table border="1" cellpadding="8" cellspacing="0" width="700px" style="background-color: Aqua">
<tr>
<td style="direction: rtl">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
<td style="direction: ltr">
F1
</td>
</tr>
<tr>
<td style="direction: rtl">
<asp:DropDownList ID="Drp_1" runat="server" ClientIDMode="Static">
<asp:ListItem Value="1">Head of household</asp:ListItem>
<asp:ListItem Value="2">Spouse</asp:ListItem>
<asp:ListItem Value="3">Child</asp:ListItem>
</asp:DropDownList>
</td>
<td>
F2
</td>
</tr>
<tr>
<td style="direction: rtl">
<asp:RadioButtonList ID="Rad_7" runat="server" ClientIDMode="Static">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
<asp:ListItem Text="3" Value="3"></asp:ListItem>
<asp:ListItem Text="4" Value="4"></asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
F3
</td>
</tr>
<tr>
<td>
<asp:Button ID="BindAgain" runat="server" Height="44px" Text="Submit" ClientIDMode="Static"
Width="207px" OnClick="BindAgain_Click" />
</td>
<td>
<asp:Button ID="btn" runat="server" Height="44px" Text="Submit" ClientIDMode="Static"
Width="207px" OnClick="btn_Click" />
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
<asp:TextBox ID="isPostback" ClientIDMode="Static" runat="server"></asp:TextBox>
<h1 style="color: Green; font-size: large; font-weight: bold; display: none;" id="nima">
Progress ...
</h1>
and this is code bihind:
protected void btn_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(4000);
TextBox1.Text = "nima";
}
protected void BindAgain_Click(object sender, EventArgs e)
{
Drp_1.SelectedIndex = 1;
Rad_7.SelectedIndex = 3;
isPostback.Text = "1";
}
when I want to check value of isPostback after postback using jQuery I get "" .this is my javascript code:
function pageLoad() {
$('#nima').hide();
$(document).ready(function () {
//alert("NIMA");
$("#Drp_1").on("change", function () {
if ($(this).val() == 2) {
if ($('#Rad_7 input:checked').val() != null && $('#Rad_7 input:checked').val() > 1 && $('#Rad_7 input:checked').val() != 2) {
if ($('#isPostback').val() == "0") {//<<<<<<<<
alert('Wrong option');
}
}
}
else {
$('#Rad_7 input').removeAttr("checked");
}
}).change();
$("#Rad_7 input").on("change", function () {
if ($(this).val() == 2) {
if ($('#Drp_1').val() != null && $('#Drp_1').val() > 1 && $('#Drp_1').val() != 2) {
if ($('#isPostback').val() == "0") {//<<<<<<<<
alert('Wrong option');
}
}
}
if ($("#Drp_1").val() != null && $("#Drp_1").val() == 2) {
if ($('#Rad_7 input:checked').val() != null && $('#Rad_7 input:checked').val() != 'undefiend' && $('#Rad_7 input:checked').val() != 2) {
if ($('#isPostback').val() == "0") {//<<<<<<<<
alert('Wrong option');
}
}
}
}).change();
});
}
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) {
$('#nima').css('display', 'block');
}
function EndRequest(sender, args) {
$('#nima').css('display', 'none');
}
where is my mistake?
thanks
Your textbox is outside of the UpdatePanel. It is not receiving the update when the postback is triggered from within the panel.

Categories

Resources