Need help converting a C#/.NET method into client-side (javascript) function

Hey Guys,

I have implemented an AJAX Toolkit CalendarExtender.  I have a method 'CheckDate' in javascript (followed a tut!) that checks to see if the user selected a date > DateTime.Now().

Well, I have a few other things to check but not sure how to do them in javascript, so I'm hoping someone here can help me.  I mean, i can somewhat convert it but it'll be too mangled, I'd rather learn the right way.  I'm attaching the code and any help will be appreciated.


1            protected string CheckDateErrors(string dateGiven)
2            {
3                // let's make sure that the date entered by user
4                // does not exceed the present date or goes back
5                // over a year.
6                // we need to try parse! 
7                DateTime userDate = DateTime.Parse(dateGiven);
8                //DateTime userDate;
10               int userYear = userDate.Year;
11               int userMonth = userDate.Month;
12               int userDay = userDate.Day;
14               // not valid! user entered future date, can't allow this to happen
15               if (userDate.CompareTo(DateTime.Now) > 0)
16               {
17                   //this.tbBeginDate.ForeColor = Color.Red;
18                   //this.tbBeginDate.BorderColor = Color.Red;
19                   return "* Cannot Enter Future Dates;";
20               }
21               // date cannot be more than one year old.
22               else if (userDate.CompareTo(DateTime.Now) <= 0)
23               {
24                   int difference = DateTime.Today.Year - userYear;
26                   // going too far back; now allowed.
27                   if (userYear < (DateTime.Today.Year - 1))
28                   {
29                       return "* Cannot Enter Past One Year: Compared Years;";
30                   }
31                   else if ((difference == 1) &&
32                       (userMonth < DateTime.Today.Month))
33                   {                
34                       return "* Cannot Enter Past One Year: Compared Months;";
35                   }
36                   else if ((difference == 1) &&
37                        (userMonth >= DateTime.Today.Month) &&
38                        (userDay < DateTime.Today.Day))
39                   {
40                       return "* Cannot Enter Past One Year: Compared Days";
41                   }
43                   return "none";
45               }
47               return "none";
49           }


Carpe Diem!
12/5/2008 9:33:02 PM 17816 articles. 1 followers. Follow

7 Replies

Similar Articles

[PageSpeed] 40
Get it on Google Play
Get it on Apple App Store


In order to validate date in javascript , you need to create a two date object's in javascript which will represent the current date and the date which you have selected by using Calander control .

Now following are the ways with which you can create a date object in javascript:-

Date() - Use the current date and time to create an instance of the object date.
Date(dateString) - Use the date specified by the string to create the instance of the date object. String format is "month day, year hours:minutes:seconds".
Date(year, month, day) - Create an instance of date with the specified values. Year is 0 to 99.
Date(year, month, day, hours, minutes, seconds) - Create an instance of date with the specified values.

I have not modified your code but I am just giving few lines from my code which you can use to validate the date . Remember you will have to put some logic from your side in the code which I have mentioned below :-

// Function to validate dates before processing
function ValidateDate()
    var returnValue = 0;
    // Todays date
    var currentDate = new Date();
    // Array decleration
    var arrayMonths = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
    var tempdate = new Date();
    // Temporary startdate object
    var tempStartDate = <Entered Date or date selected from calander control>; // I am using the following format dd-MMM-YYYY , if you are using different  format then you need to modify the next three lines to get extarct year , day , month

    var startYear = tempStartDate.substring(tempStartDate.lastIndexOf('-')+1); // get the year
    var startDay =  tempStartDate.substring(0 , tempStartDate.indexOf('-'));   // get the day
    var startMonth =  tempStartDate.substring(tempStartDate.indexOf('-') + 1 , tempStartDate.lastIndexOf('-'));  // get the month
    // Start date
    var startDate = new Date(startYear , arrayMonths.indexOf(startMonth), startDay); // Create an instance of date object in a format which javascript understands( javascript representaion of selected date)

    // After this you have to implement the logic of date validation
    // For this you can make use of various javascript method like getYear() , getDay() etc on date object to extract relevant information
    // Also once you have instantiated date in the form of javascript object you can use arithmatic operators like < , > , >= , <= , === , !== etc 


And while you are validating your selected date following link will be of great help to you :-

Also there can be various ways by which you can validate date , the above approach may seems more complex and cumbersome but I learned a lot from the above approach . If you can get some more efficient method please provide the same in current thread .

Pawan Mishra
“The greatest compliment that was ever paid to me was when one asked me what I thought, and attended to my answer.” - Henry David Thoreau
12/6/2008 5:47:15 AM


 thanks a LOT for the help.  I've been using your help as well as the link to convert my method to a javascript function.  I am stuck on one part though.



1    else if(sender._selectedDate <= currentDate)
2                {
3                   //var userDate = (Date)(sender._selectedDate);
4                    var yearDay = usersender._selectedDate.getDate();
5                    var userMonth = sender._selectedDate.getMonth();
6                    var userYear = sender._selectedDate.getYear();
8                    int difference = currentYear -  userYear;
10                   // going too far back; now allowed.
11                   if (userYear < (currentYear - 1))
12                   {
13                       alert("Error: No Dates Past A Year Allowed");
14                   }

 The problem is located in lines 3-6.  I need to extract the month, year, and date from sender._selectedDate.  I'm not sure how to do this part in JS.  Can anyone help me, please?  Thanks.

Carpe Diem!
12/8/2008 5:16:46 PM


getDate() , getMonth() etc kind of functions will work only with date whose format is actually compatible with javascript date format . For eg in your javascript function give :-

var date = new Date();

alert(date); --> result will be something like this " Tue Dec 9 smthn smthn " .

Since in my application the date format of calander extender control which i was using was dd-MMM-YYYY so i had to maually write the code to extract the specific information which is day , month and year and then pass these details into the constructor of date class of javascript .

If you can tell me which format you are using in you application I can then help you in getting through your problem.

Pawan Mishra
“The greatest compliment that was ever paid to me was when one asked me what I thought, and attended to my answer.” - Henry David Thoreau
12/9/2008 6:38:26 AM

Hi Pawan,

Thanks a lot for your help.  You've been extremely helpful.  My date format is MM/dd/yyyy.  Looking at your example code, which somehow I missed!, I believe I know what to do.  I will update this post in a little bit.  You rock!

Carpe Diem!
12/9/2008 1:45:23 PM

I'm still having issues and have a few questions.  I will first paste the code:


1    var userDate = sender._selectedDate;
2    alert("userDate: " + userDate);
4    var hi = userDate.substring(1, 3);
5    alert("hi!");
6    var userYear = userDate.substring(userDate.lastIndexOf('/')+1); 
7    alert("userYear/lastIndexOf: " + userDate.substring(userDate.lastIndexOf('/')+1));
9    var userMonth =  userDate.substring(0 , userDate.indexOf('/'));  
10   var userDay =  userDate.substring(userDate.indexOf('/') + 1 , userDate.lastIndexOf('/')); 
11   alert("MM/dd/yyyy: " + userMonth + "/" + userDay + "/" + userYear);
Ok, first regarding what format I'm  using.  This is the exact code in designer:


a    <cc1:CalendarExtender ID="CalendarExtender2" runat="server" TargetControlID="tbEndDate"
b                               PopupButtonID="Image2" OnClientDateSelectionChanged="checkDate" Format="MM/dd/yyyy" />

 Lines 1 & 2 execute.  The alert box shows me this format "Thu Dec 4 00:00:00 EST 2008".  Should it not show me 12/04/2008..?   Have I confused something here?  Lines 4 & 5 were added to see wth was going on since I kept getting the error in IE "Object does not support this method or property".  Since line 6 uses substring and indexOf, I had to determine what method isn't working properly.  Turns out line 4 is where the code craps out.

 Pawan or anyone else, can anyone help me out here?  I am using IE 7 (not by choice, but this is what 99% of our users use here).

Carpe Diem!
12/9/2008 5:21:36 PM


You can check the following code , I have written to modify to validate of format MM/dd/YYYY :-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TextChanged.aspx.cs" Inherits="Admin_TextChanged" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" >

<head runat="server">


<script language="javascript" type="text/javascript">

// Function to validate dates before processing

function ValidateDate()


var returnValue = 0;


// Todays date

var currentDate = new Date();


// Temporary startdate object

var tempStartDate = $get('txtCal').value;

var toYear = tempStartDate.substring(tempStartDate.lastIndexOf('/')+1);

var toMonth = tempStartDate.substring(0 , tempStartDate.indexOf('/')); var toDay = tempStartDate.substring(tempStartDate.indexOf('/') + 1 , tempStartDate.lastIndexOf('/'));

// Start date

var startDate = new Date(toYear , toMonth - 1 , toDay);


if(startDate > currentDate)


" Start date cannot be greater than todays date ");


// Here you can carry on your validation I have just validated one scenario where selected date should not be greated than todays date


</script> </head>


<form id="form1" runat="server">


<ajax:ScriptManager ID="script1" runat="server" EnablePartialRendering="true"></ajax:ScriptManager>

<asp:Button runat="server" ID="btnClick" Text="Button" OnClientClick="ValidateDate()" />

<asp:TextBox runat="server" ID="txtCal"></asp:TextBox>

<ajaxToolkit:CalendarExtender BehaviorID="Cal1" ID="Cal" TargetControlID="txtCal" runat="server" Format="MM/dd/yyyy"></ajaxToolkit:CalendarExtender>


</form> </body>



Let me know if you need some more help :-) ....

Pawan Mishra
“The greatest compliment that was ever paid to me was when one asked me what I thought, and attended to my answer.” - Henry David Thoreau
12/10/2008 4:38:36 AM


 var tempStartDate = $get('txtCal').value;

does the trick!  Great.  Last question:


The above line.... what if I want to leave the textbox blank?  I tried '' and ' ', but got an error.  Got ideas? 


Carpe Diem!
12/10/2008 4:35:43 PM

Similar Artilces:

converting to from offered me some sample code when I signed up with them the only problem is the sample code is in but my page that they type all of their credit card into is <code><%@ Import Namespace="System.Net" %> <%@ Import Namespace="System.IO" %> <script language="C#" runat="server"> void Page_Load(Object Src, EventArgs E) { myPage.Text = readHtmlPage(""); } private String readHtmlPage(string url) { ...

Developed WebService 1.1 for Client 1.1. Getting error "Server was unable to process the Request" Pls Help
Hi., I developed Microsoft Web Services2003 for the Client Application 2003. When it runs in 5 machines it gives good performance and has no errors. But if i run the same application in about 80 client machines. Getting error "Server was unable to process the request". I use Sql Server 2005 as my database. I get error even when i login at a time for about 25 users. Tried modifying machine.config too. But went unsuccessful. Live Server is 2003 using IIS 6.0 I use very expensive data handling.  Its very urgent pls help. Have to post in Live Server. Thank u., ...

need help converting C# to
need help converting C# to C# version is below ================================ namespace LicensedControls { [ LicenseProvider(typeof(ExpiringLicenseProvider)) ] public class ExpiringLicensedLabel : Label { public ExpiringLicensedLabel() { LicenseManager.Validate(typeof(ExpiringLicensedLabel)); } } } my attempt to get vb ========================= Namespace LicensedControls <LicenseProvider(GetType(ExpiringLicenseProvider))> Public Class ExpiringLicensedLabel ...

Need help converting C# to VB.Net
I'm new to the .Net world, I have a little experience in VB.Net and that's what I'm focusing on.  I have a C# function I'm converting to VB.Net. I've got it all done except for the following.  For Each x As System.Collections.DictionaryEntry In e.NewValues    p = New System.Data.SqlClient.SqlParameter("@" + x.Key, x.Value)    c.Parameters.Add(p) Next On the line "p = New ...."  I'm getting "Overload resolution failed because no accessible 'New' can be called without a narrowing conversion" I understand the error message, I just don't know the proper s...

help, need this code converted to .net functions
I have the following code. I know that there is probably a completing different way of handling this in What i need is this code converted to <% '****************************** ' Crypt.asp '****************************** Dim g_Key Const g_CryptThis = "12345678912345" Const g_KeyLocation = "" g_Key = "somekey" Response.Write "<p>ORIGINAL STRING: " & g_CryptThis & "<p>" Response.Write "<p>KEY VALUE: " & g_Key & "<p>" Response...

How to call server side(C#) function from Client side(Javascript) function?
Hi i have used below functions,  function HandleOnClose() {// this function will be called after clicking browsers close button in Internet explorer if (event.clientY < 0) { event.returnValue = 'Are you sure you want to leave the page?'; } // if he clicks ok then i need to call one server side function in this instance.. else not. } <body onbeforeunload="HandleOnClose()" leftmargin="0" rightmargin="0">other controls in page..</div>  How to achieve this? Thanks MS AJAX Extensions would be the option of choice here. Combined with webservices you can...

Help needed in converting C# code to VB.Net?
I am trying to convert the C# code below to VB.Net. ( I know in VB.Net the size of array is specified using the highest array index rather than actual size) Will char[] chars = new char[62]; become 'Dim chars(61) as new Char'? Will byte[] data = new byte[1]; become 'Dim data(0) as Byte'? Will data = new byte[size]; become ReDim Preserve data(size - 1) OR ReDim  data( size -1) ? What will result.Append(chars[b % (chars.Length - 1)]);  convert to in VB.Net?  Basically I am trying to convert the C# code to VB.Net. If someone can help me in doing the complete translati...

help needed to convert this sub routine from VB.NET to C#
i need to convert the following sub routine to a c# function. not familiar with unfortunately. have tried but failed any help appreciated. thanks! Public Sub DefaultButton(ByRef Page As System.Web.UI.Page, ByRef objTextControl As TextBox, ByRef objDefaultButton As Button) Dim sScript As New System.Text.StringBuilder() sScript.Append("<SCRIPT language=""javascript"">" & vbCrLf) sScript.Append("function fnTrapKD(btn){" & vbCrLf) sScript.Append("if (document.all){" & vbCrLf) sScript.Append(&quo...

I need help in converting a C# file to VB.NET equivalent.
Hello,   Here is the code snippet I got strucked at. I am unable to convert the below line of code to its equavalent code. could some one please help me with this? [DataObjectMethod(DataObjectMethodType.Select, true)]         static public List<RoleData> GetRoles()         {             return GetRoles(null, false);         } Thanks -L It would be something like this: <DataObjectMethod(DataObjectMethodType.Select, True)> _Public Shared Function GetRoles() As List(Of RoleD...

Sending SMS using or using or
Hi  My requirement is I hav one csv file with these fields id,mobilenum,messgae,status.intiallu staus is 0. once i read the all fileds and take that mobile number.using tat mobile number  i need to send sms .after sending sms i shuld change status as 1 How to send sms thru coding (please dont provide any links.if it is provide also please give working links becox i checked codeproject .i didnt get any nice link. and also provide the how to update the status field im csv file   Thank ssandhya   To send SMS, you need some third party SMS providers. if you consul...

Need Help. Convert C# script -> VB.NET script
Please please help me .... conver this script into VB.NET script. Thank You protected override object LoadPageStateFromPersistenceMedium() { object o = null; try{ o = base.LoadPageStateFromPersistenceMedium(); } catch {} return o; } Thanks & Regards--"Don't just always label good or bad about something, always have something is invisible from nude eyesight. "...

trying to rewrite a small C# function to Need help please?
Can someone help me rewrite this c# code to I think I have most of it right but I am stuck.       [WebMethod]public string[] GetCountryInfo(string prefixText){int count = 10; string sql = "Select * from customer Where company like @prefixText";SqlDataAdapter da = new SqlDataAdapter(sql,"Data Source=MISFS;Initial Catalog=QuoteSystem;Integrated Security=True");da.SelectCommand.Parameters.Add("@prefixText", SqlDbType.VarChar, 255).Value = prefixText+ "%"; DataTable dt = new DataTable(); da.Fill(dt); string[] items = new s...

Converting from to
Hello I have recently purchased VBGolds RawDataPrinter which should allow users to print directly to label printers on our network directly from a c# web form.  Unfortunately they only supply examples and I have need of c#.  The component has been installed on our web server.  This is some code that they have supplied as examples in   "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" >"Head1" runat="server&qu...

Hi theretrying to complete a login page.  The example I have is written in visual basic, can you please convert the following statement into C# for a submit button (transferring data to a database!!):Sub btnSubmit_Click(sender As Object, e As EventArgs)   If Page.IsValid then      InsertGuestbookEntry(name.Text, email.Text, message.Text)      Response.Redirect("ViewGuestbook.aspx")   End IfEnd SubAlso, the following for retrieving data from a database into a drop down menu:Sub Page_Load (sender as ...

Web resources about - Need help converting a C#/.NET method into client-side (javascript) function -

Client-side scripting - Wikipedia, the free encyclopedia
... different and changing content depending on user input, environmental conditions (such as the time of day), or other variables. Client-side ...

Senior Search Manager - Client Side!!
... strategy insight for senior IT management - resources to understand and leverage information technology. Senior Search Manager - Client Side ...

Account Manager - Client Side - Previous Agency Experience Welcome!!
Computerworld Australia is the leading source of technology news, analysis and tools for IT decision makers, managers and professionals.

Media Sales Executive - Client Side!!
Technology news and reviews for business and home.

PPC Paid Search Manager - CLIENT SIDE
Defining Technology for Australia's IT Leaders. PPC Paid Search Manager - SEM - **CLIENT SIDE** Sydney CBD Location Client side!! SEM/PPC/Paid ...

How Basecamp Next got to be so damn fast without using much client-side UI
When we started working on Basecamp Next last year, we had much internal debate about whether we should evolve the existing code base or rewrite ...

Seven Tips for Pitching From the Client's Side of the Table
I had a chance to sit on the other side of the pitch table. Here is what I learned.

Client-side coding: How to prevent malicious use?
Applications that run on a user-controlled device cannot be perfectly protected.

The client side
... regarding the professionals you seek to assist. Even better if you possess that understanding yourself, having worked on the client side. I'm ...

Ecommerce traffic being hijacked by client side malware
According to new research 15 to 30 percent of eCommerce site visitors are infected with Client Side Injected Malware (CSIM) that causes them ...

Resources last updated: 12/12/2015 9:46:52 AM