Javascript to validate start date and end date in asp.net - c#

I have written a JS that should check that start date is less than end date. If not, alert should be thrown
The JS is written as;
function DateValidation(startDate, EndDate) {
debugger;
var stdate = startDate;
var enddate = EndDate;
if (stdate!= '' && enddate!='') {
if (stdate > enddate) {
alert('Start date cannot be greater than end date');
return false;
}
else {
return true;
}
}
}
This JS gets fired when i am clicking a button as "Show Report".
Problems that i am facing
JS doesn't validate the date correctly. What am i missing? i am passing date from the textbox
The JS doesn't fired up when clicking button for the first time. it fires when clicking the button second time
Plus, i have registered the JS as below;
btnShowReport.Attributes.Add("onclick", "return DateValidation('" + txtStartDate.Text + "', '" + txtEndDate.Text + "');");
Is the above code correct? What is the correct place to register the JS?
Please guide.. thanks!

You need to parse the string values to dates
if (startDate!= '' && EndDate!='') {
var stdate = Date.parse(startDate);
var enddate = Date.parse(EndDate);
if (stdate > enddate) {
alert('Start date cannot be greater than end date');
return false;
}
else
{
return true;
}
}
Without further code it's hard to tell why your button only fires the event on the second click. Is your button disabled to start with?

Use Date.parse. What you are doing is checking whether a string is greater than another string.
Also the script will take only whatever is there at the first time in txtStartDate.Text, txtEndDate.Text EVERY time the script runs.
Why? You have not correctly understood server side and client side execution.
This line in your code,
btnShowReport.Attributes.Add("onclick", "return DateValidation('" + txtStartDate.Text + "', '" + txtEndDate.Text + "');");
registers the script to the page passing the text in those text boxes.
You have assumed that each time the text changes in the text box, the method will take the new values and do the date calculation.
However your script would look something like this, assuming the two text boxes are empty when the page is loaded. You can verify this by checking the page source.
<inputid="btnShowReport" ... onclick="return DateValidation('','')>
Because JavaScript is run at client side, the server is not contacted each time to get the current values of those text boxes.
What you can do is pass the text boxes it self to the method. Something like
return DateValidation(txtStartDate.ClientID, txtEndDate.ClientID);
and from the method you can access it like shown below
function DateValidation(txtStartDate, txtEndDate) {
debugger;
var stdate = Date.parse(txtStartDate.value);

I think the problem is that you're not comparing dates - you have just declared them as vars without a type so they're essentially Strings.
Check out the Date.parse() method.

Adding to what the previous 2 guys have answered with, you have to parse the dates. You also need to validate that they are even dates. I use this library often when working with dates on the client side:
http://www.datejs.com/

The main problem is how you register the event. You are creating a string with code that contains string literals with the values, which means that you get the values from the textboxes at the time that you create the string, not at the time that the event is activated. You have to make a postback before the code is updated with the current values, that is why it doesn't work on the first click.
Create code that gets the values at the time of the click:
btnShowReport.Attributes.Add("onclick", "return DateValidation(document.getElementById('" + txtStartDate.ClientID + "').value, document.getElementById('" + txtEndDate.ClientID + "').value);");
Another possible problem is that the code doesn't compare dates, it compares strings. Some date formats are comparable as strings, e.g. ISO 8601 based formats: "2010-12-31" < "2011-01-01", but other date formats has to be parsed into dates to be compared, e.g. "31/12/2010" > "01/01/2011".
Parse the dates after checking that they are not empty:
...
if (startDate != '' && EndDate != '') {
var stdate = Date.parse(startDate);
var enddate = Date.parse(EndDate);
...

Related

String comparison fails even when visually checked

I added a function to my application recently that reads a date from a downloaded file and finds the difference in days between current date and the date from the file. When done, it is displayed in a label in one of my forums.
There is an exception: if the string in the file equals "Lifetime", it should not process it as a date and follow alternate logic. But when I try to check if the string is "Lifetime", it does not return true, even if the string = "Lifetime".
EDIT: I fixed the FormatException with help from Nisarg. Now, my labels aren't changing to the values. This is the problem.
EDIT2: I feel stupid. I found out that I was initiating Main twice in one function, then using main1 to switch between forms and main to set the labels.
This is why the labels weren't working right. Thanks Nisarg and all other contributors.
Code example:
string subScript = File.ReadAllText(Path.GetTempPath() + txtUsername.Text + ".txt");
Main main = new Main();
double dSubLeft;
main.dateLabel.Text = subScript;
if (subScript == "Lifetime") // it bypasses this, apparently blank
{
main.daysLeftLabel.Text = "Expires: Never";
}
if (subScript != "Lifetime") //Goes here and throws error saying subScript is not valid DateTime
{
dSubLeft = Math.Round(Convert.ToDouble(Convert.ToString(((Convert.ToDateTime(subScript)) - DateTime.Now).TotalDays)));
string sSubLeft = Convert.ToString(dSubLeft);
main.daysLeftLabel.Text = "Expires: " + sSubLeft + " Days";
}
While using files you often get trailing blank spaces or newline characters. Try trimming the string before comparing it to Lifetime:
subScript = subScript.Trim().Trim(Environment.NewLine.ToCharArray());
Another (less likely) problem could be with the comparison itself. In C# the comparison in case-sensitive. So if you're comparing lifetime with Lifetime they are considered unequal. You should rather use case-insensitive comparison:
if(string.Equals(subScript, "Lifetime", StringComparer.OrdinalIgnoreCase))
OR
if(subScript.ToLower() == "lifetime")
You could also check if the subScript you are getting from the file is a valid date or not using DateTime.TryParse.
string subScript = File.ReadAllText(Path.GetTempPath() + txtUsername.Text + ".txt");
Main main = new Main();
double dSubLeft;
main.dateLabel.Text = subScript;
DateTime subScriptDate;
if(!DateTime.TryParse(subScript, out subScriptDate))
{
main.daysLeftLabel.Text = "Expires: Never";
}
else //Goes here and throws error saying subScript is not valid DateTime
{
dSubLeft = Math.Round(Convert.ToDouble(Convert.ToString((subScriptDate - DateTime.Now).TotalDays)));
string sSubLeft = Convert.ToString(dSubLeft);
main.daysLeftLabel.Text = "Expires: " + sSubLeft + " Days";
}
I think it is because main is the starting point of a program in C#, make another methodname if you donĀ“t want it to reset things from where the program is supposed to start from
That is my guess only, make a breakpoint in the beginning of your code and check through what info you get from each row in the code
Almost certainly, the actual content of the string is not actually the string "Lifetime". Probably because of white-space on either side. Try trimming.
Relevant edit:
if (subscript.Trim() == "Lifetime")
{
main.daysLeftLabel.Text = "Expires: Never";
}
else // don't retest for the opposite condition
{
...
As you can see, this thing is awfully fragile, because the string could still be many things that aren't a valid DateTime. Smells like homework, but there you go...
i think you should use
if(string.Equals(subScript, "Lifetime", StringComparer.OrdinalIgnoreCase))
{
//statement
}
else
{
//statement
}

Checking Regional and language setting in asp.net [duplicate]

Ok im sitting with this issue kind of stupid but I don't know how to google this for the solution.
Lets say i have a database with values inside e.g 1000.00 .
I convert it to double using Convert.ToDouble();
On my PC it works, however on my server it doesn't unless I change to string and replace . with , .
i.e 1000,00 works on the Server but not 1000.00
But if I do Convert 1000,00 to Double I cannot save it again in the database without taking it back to string and replace , with .
How can I overcome this problem.
OS is win7, server is SQL Server 2012.
DataTable DT = SQLServer.ExecuteQueryWithResults("EXEC CalculateMonthlyBallance");
foreach (DataRow row in DT.Rows)
{
ClientCompany CC = Data.Companies.First(C => C.CompanyID == row[0].ToString());
Finance Saldo = new Finance(CC.CompanyID, "Monthly Saldo", "Monthly Saldo", 0, 0, new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1), F_Type.Saldo, -1);
double rv = row[3].ToDouble();
MessageBox.Show("Company ID : " + CC.CompanyID.ToString() + " " + rv.ToString());
if (rv > 0)
{
Saldo.Debit = rv;
}
else if (row[3].ToDouble() < 0)
{
Saldo.Credit = -rv;
}
MessageBox.Show(Saldo.Debit + " " + Saldo.Credit);
CC.Finances = RetrieveFinances(CC.CompanyID).ToList();
if (CC.Finances.Count(S => (S.F_Type == F_Type.Saldo) && (S.Date == new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1))) == 0)
{
CC.Finances.Add(Saldo);
CaptureFinancial(Saldo);
}
}
The locale setting, specifically the regional settings that govern what symbol is used as a decimal point, are influencing the conversion. To avoid that, you need to perform a culture invariant conversion so that the locale setting on your machine does not play a part. For example:
double value = double.Parse(stringValue, CultureInfo.InvariantCulture);
That said, I do wonder why you are storing floating point values as strings in the first place. It's best to convert user input into its natural form at the earliest possible moment, and only convert back to string as late as possible.
See Convert.ToDouble(string,CultureInfo)
This is because of your CultureInfo. Apparently, your PC is using periods for decimal notation, while your server is using commas. if you try to convert one of them using the other method, you get this issue.
Solution: Convert.ToDouble() has an extra overload which allows you to pass a cultureInfo for conversion. Or you can just save your variable in the database as a float or decimal.

Change text color of old date using javascript

I am using javascript to display a dashboard with various charts and graphs and when you click a chart you can drill down and see information about it.
At the bottom I also have a date of when the charts were last updated.
How can change the text color of the text when the 'last updated' date has passed?
I could do it in C# with the following code (something like it, didn't test it), but not sure on how to go about it using javascript.
if(text.Date < DateTime.Now)
{
text.Date.backcolor == Color.Red;
}
You can do something like this:
var dt = document.getElementById("yourDate"); //get your date
var today = new Date(); //get date today
if(dt.value < today )
{
dt.style.color="red";
}
It would be easier to answer if you disclosed how you are putting the date there and what format it is in.
Otherwise check out the Date object in javascript. It could be as simple as:
var oldDate = new Date(unix_timestamp); // you'd provide this from your db?
if(oldDate.getTime() - new Date().getTime() < 0)
document.getElementById('your_date_element?').style.color = 'red';
If you're putting the date there via php or something, you could simply change the output color at that time using a php solution ( strtotime and time(), for example)
EDIT: but yeah that'll always be the case lol.

C# If statement where date is this month

string month = DateTime.Now.Month.ToString();
string CommandText = "SELECT slocref.slocname, partstuff.quantity, partstuff.currency, partstuff.postingdate" + " FROM partstuff INNER JOIN slocref ON partstuff.sloc = slocref.slocvalue";
This is the code to get date and month.
if (Regex.IsMatch(rdr["postingdate"].ToString(), "0" + month + "*"))
{
if (rdr["slocname"].ToString() == "Answer/Slatwall")
{
string quantity = rdr["quantity"].ToString();
string currency = rdr["currency"].ToString();
answertotalmonth += float.Parse(currency);
label100.Text = "$" + answertotalmonth.ToString("#,##0.00");
}
}
This is just an example of the code that is run by the if statement.
But the if statement needs to get all of the July information and add it up. So from 07/01/2012 to 07/31/2012. I cannot change the SQL because it messes up the rest of the program. I tried to get the current date, add the 0 in front of it, then use a wildcard.
Need a little direction on this if statement.
Let me clarify this post. The "postingdate" value comes from FileHelpers. Importing a text file by fixed width into these values. The postingdate value looks like "07/16/12"
So, I want to get this current month, and then if a postingdate value has that month's value, run the if statement code.
Why would you do this?
if (Regex.IsMatch(rdr["postingdate"].ToString(), "0" + month + "*"))
If rdr["postingdate"] is supposed to be a date, convert it to a date time and do a sensible comparison.
if(DateTime.TryParse(rdr["postingdate"].ToString(), rdrDateTime))
{
// proceed as planned
if (rdrDate.Month == DateTime.Now.Month)
{
// and so on.
}
}
Not sure I understand you problem correctly but why don't you just match the DataTime's month property:
if( date.Month == month)
{
//your code...
}
Also like mentioned above, you can parse the text as a date. But if you are just interested in just the month that may not be necessary.
Edit: As mentioned in the comments, you would have to check the year as well. So it would be better to pares as a full DateTime object.

Jquery Datepicker Issues with adding events

I am trying to make a date picker with a bunch of events that I pull from an rss feed. To make the datepicker I pretty much copy this post: jQuery UI Datepicker : how to add clickable events on particular dates?
The issue I am having is that I keep getting the error event.Date is undefined. I think this may be because of how I am passing in the dates. The dates come from a collection of strings on page load, that are converted like this:
//Convert objects
currentEventInformationString = JsonConvert.SerializeObject(currentStoreEventInformation);
eventDatesString = JsonConvert.SerializeObject(storeEventDates);
Where currentEventInformationString is a collection of strings containing a title, description, and link and eventDateString is a collection of strings that are dates (I get it from a method that returns date.ToShortDateString();
I then add all of my dates to an event array like so (in js):
//Adds each event to the date picker
for (var x = 0; x < eventDates.length; x++) {
//Adds event
events[x] = [{ Title: currentEvents[x].title.toString(), Date: new Date(eventDates[x].toString()) }];
}
I have then tried running a console.debug(events[x].Title + " " + events[x].Date); but every time I undefined undefined
When I run a debug like this:
console.debug(currentEvents[x].title.toString() + " " + eventDates[x].toString());
I get the correct values so I know that that is not the issue.
Any suggestions?
Also: I know that the question seems vague so I tried to include as much sample code as I thought was relevant. If you need more let me know. To see how the date picker is made look at the link.
Edit Here is how I declare events:
//Current event
var events = new Array(eventDates.length);
I think you have a stray set of brackets. This:
events[x] = [{
Title: currentEvents[x].title.toString(),
Date: new Date(eventDates[x].toString())
}];
Is assigning an array that contains one object literal to events[x] but I think you just want to assign an object to events[x]:
events[x] = {
Title: currentEvents[x].title.toString(),
Date: new Date(eventDates[x].toString())
};

Categories