date validation - asp.net

can any one tell me the code to validate the date field in signup form(which shd also validate the leap year and no of days in each month

That depends on the input but suppose you have a string input for the whole date then you could try something like:
try
{
DateTime parsedDate = DateTime.Parse(incomingDateString);
}
catch
{
throw new Exception("Incoming Date string could not be parsed as a DateTime");
}
Alternatively if you have three integers as strings coming in from the form then you would replace the DateTime.Parse with
DateTime parsedDate = new DateTime(Int32.Parse(yearString), Int32.Parse(MonthString), Int32.Parse(DayString));
and allow the DateTime constructor take care of the details of analyzing days of month and leap years. You could be more sophisticated and use Int32.TryParse and provide more specific error messages and checks for null strings if thats what you need.

You can make sure you get a valid date by adding a calendar control or a date picker control. This will avoid having to add extra validation just to validate this field.
If you don't want to use a calendar control or date picker, you can use DateTime.Parse and place it inside a Try, Catch block.
dateString = YourDateField.Text;
try {
dateValue = DateTime.Parse(dateString);
}
catch (FormatException) {
Console.WriteLine("Unable to convert, this is not a valid date '{0}'.", dateString);
}
Hope this helps.

Related

How to force RFC3339 string for all datetime for queries upon display as API?

Using Cake 3.2.4
What am I getting now?
Whenever a query is executed and there is a datetime field, it will be displayed as RFC2822 string.
e.g. "2016-07-18T09:00:00+0800"
What do I want?
I want RFC 3339 string
e.g. "2016-07-18T09:00:00+08:00"
What did I try?
$paginationQuery->formatResults(function (\Cake\Datasource\ResultSetInterface $results) {
return $results->map(function ($row) {
$datetime = $row['start_date'];
$row['start_date'] = $datetime->format(\DateTime::RFC3339);
return $row;
});
});
I kinda forced the original datetime object to display as string.
Okay, so what's wrong?
I am unsure if it's wrong to do so. As you can see clearly, the original value for $row['start_date'] is actually a datetime object. Not a string.
Can I keep the value as datetime object but when it gets displayed as api, it uses the RFC3339 format?

ASP.NET MVC5 stores date in wrong format

last days I have a quite hard time to convince MVC5 project to work with dates as I would like to. After intensive googling I've tried numerous attepmts to make it work properly, but without success.
Here is the problem:
I need to display and edit dates on my webpage in format dd.MM.yyyy (i.e. 15.07.2015). For editing I also need to use jquery ui datepicker. The thing here is that I've been able to successfully set that datepicker to display date in requested format, also the jquery validation is now correctly validating the date in given format. So as for UI so far so good. The problem appeared in moment, when I clicked submit button - there was an error message like:
The value '15.07.2015' is not valid for Start Date.
After brief investigation I've found that when the date is passed to server it has switched format - instead of dd.MM.yyyy the date is treated like MM.dd.yyyy. In other words the error pops up only when the day part of date is higher than 12.
Here are some highlights from my code:
In my model for date I have this:
[Required]
[Display(Name = "Start Date")]
[DataType(DataType.Date)]
[UIHint("Date")]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
public DateTime DateStarts;
Which I believe is everything I need to do to make that date display in specified format and also force users to fill the textbox with date in right format.
As given in [UIHint("Date")], I have my own template for rendering textbox for editing date. The implementation of that template is following:
#model Nullable<DateTime>
#{
DateTime dt = DateTime.Now;
if (Model != null)
{
dt = (System.DateTime)Model;
}
#Html.TextBox("", dt.ToString("dd.MM.yyyy"), new { #class = "form-control datecontrol", type = "text", data_val_date = "Field must have format dd.MM.yyyy" })
<i class="fa fa-calendar form-control-feedback lowerzindex"></i>
}
The jquery datepicker has following implementation:
$('.datecontrol').datepicker({
onClose: function () { $(this).valid(); },
minDate: "-1M",
dateFormat: "dd.mm.yy",
});
So even the datepicker knows how the format should look like.
The last component is the validation by jquery.validation:
$.validator.addMethod(
'date',
function (value, element, params) {
if (this.optional(element)) {
return true;
};
var result = false;
try {
$.datepicker.parseDate('dd.mm.yy', value);
result = true;
} catch (err) {
result = false;
}
return result;
},
''
);
I know that the date is passed to server in some culture neutral format, but I thought that when I decorated code on numerous places with the requested format, this will ensure that the conversion into that culture neutral format will be done right. Or am I missing something else ?
Thanks
Your problem lies in the fact that you have not set proper Culture for your application. Your request end-up executing under culture that has month-day-year order (probably under en-US) causing you a problem.
The easiest solution is to set set the culture that actually has day-month-year order and . as date separator in your web.config, for example:
<configuration>
<system.web>
<globalization uiCulture="de-DE" culture="de-DE" />
...
https://msdn.microsoft.com/en-us/library/bz9tc508%28v=vs.140%29.aspx
The MVC uses current culture when parsing and binding posted data to your models/parameters.
It is advised to use same date separator across entire scope - html, client, javascript, server culture, ...

Binding time values to asp.net GridView

I need to bind time values to my gridview. For example, if the time is 13:00, I need to display it as 13-00 in the grid. But it displays as 01-00. How do I resolve this?
You can use GridView.RowDataBound Event to achieve it. Format your time string as you want and assign to to the grid view cell.
You can use date formats to convert datetime into 24-hrs format.
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Text = DateTime.Now.ToString("MM/dd/yyyy HH:mm");
}
}
You need to convert the value into 24-hour format (for instance by selecting a different culture for your application) or simply create some converter class that will convert this for you. There are multiple resources to learn from.
Something like this should work:
DateTime localTime = DateTime.Now;
// 24 hour format -- use 'H' or 'HH'
string timeString24Hour = localTime.ToString("HH:mm", CultureInfo.CurrentCulture);
Taken from another answer here in SO Convert AM/PM time to 24 hours format?
If your culture uses 12-hour format, use a different culture info for the parsing that supports 24-hour format.
Of course you'd probably like to wrap this in a getter property so it will be available for the binding
public string DateIn24HourFormat
{
get
{
return MyConvertFunction(this.Time);
}
}
You get the idea.
Give your Time format in DataFormatString property in BoundColumn.
Apply format as
{0:HH-mm}
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.dataformatstring.aspx

Convert string date to system datetime in C#

I want to convert string date to system datetime in C#. The user enters date through textbox and it should be converted as to datetime. I trid following code but its not working...
DateTime ToDate = Convert.ToDateTime(txtToDate.Text);
DateTime FromDate = DateTime.Parse(txtFromDate.Text);
It shows the following exception
"String was not recognized as a valid DateTime."
How to do this...???
You could use DateTime.ParseExact(). That way you can specify the format of the input string, so it will be parsed correctly, for example:
dateString = "Sun 15 Jun 2008";
format = "ddd dd MMM yyyy";
try
{
DateTime result = DateTime.ParseExact(dateString, format, CultureInfo.CurrentCulture);
}
catch (FormatException)
{
}
whatever user enters in your textbox that should be in valid date format, otherwise write your own function to make it in valid format. then Convert it into DateTime format .
for different format you can check this :
http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx
for more help you can check similar question on this site :
Validate a DateTime in C#
You can of course parse the user's input and rely on the users to always enter a correct date. But I'd recommend to use a specific control for entering a date, such as the calendar control of the ajax control toolkit.
By using such a control, you can prevent invalid input and it's also much easier for the user. If you search for DatePicker or similar, I'm sure you can find lot's of other similar controls.
Ask the user to enter his datetime in a particular format into textbox i.e., either "ddMMyyyyhhmmss" or "dd/MM/yyyy hh:mm:ss tt" or "dd-MM-yyyy hh:mm:ss tt" or some other formats and use the help of following code to convert in to a Valid datetime.
DateTime ToDate = DateTime.ParseExact(txtToDate.Text, <User DateTime format as String>,
System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None)
Instead, if the above coding makes complicated then you can try DateTime.TryParse() also
First of all you have to validate text box value that it is valid or not, you can use ajax MaskeditExtender control for that and restrict the use enter only require date formate.
DateTime dt = Convert.ToDateTime(date);
here date is in string.

Adobe Flex date

Hi I am having a problem in date.
I am having a custom dateChooser.
In the dateChooser component highlights some holidays and at the same time lists the holidays in a container.
The Problem is the date I am displaying in the container is not in ascending order could some one please help.
Link for the demo application with view source enabled
http://125.22.254.206/clients/flexdemos/calendardemo/calendardemo.html
The said logic is implemented in ExtendedDateChooser.as under custome folder.
Are you trying to sort the date in the 'holidayView' vbox?
You cant compare and sort two dates. You can use the date comparison method given below (search the web to find a better one).If the control in the vbox to display holidays is a datagrid, using
<mx:DataGridColumn
headerText="Created Date"
date="createdDt"
sortCompareFunction="date_sortCompareFunc">
</mx:DataGridColumn>
in the tag attribute will result in sortedDate
private function date_sortCompareFunc(itemA:Object, itemB:Object):int
{
/* Date.parse() returns an int, but
ObjectUtil.dateCompare() expects two
Date objects, so convert String to
int to Date. */
var dateA:Date=isoToDate(itemA.createdDt);
var dateB:Date=isoToDate(itemB.createdDt);
return ObjectUtil.dateCompare(dateB, dateA);
}
private function isoToDate(value:String):Date {
var dateStr:String = value;
dateStr = dateStr.replace(/\-/g, "/");
dateStr = dateStr.replace("T", " ");
dateStr = dateStr.replace("Z", " GMT-0000");
return new Date(Date.parse(dateStr));
}
I think, you cant sort by Date.
First, I can't see the container in your app.
My way would be to parse the date in to milliseconds since 1970
parse(date:String):Number
Then you can sort it by some logic.
BR
Frank

Resources