Datetime validation with custom format. Troubles with '.' separator - validation

In my web application (asp.new mvc) I try to make validation for date field.
If I use this
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? PeriodBeginFrom { get; set; }
or this
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")]
public DateTime? PeriodBeginFrom { get; set; }
it works. But if I try to separate using '.' separator
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yyyy}")]
public DateTime? PeriodBeginFrom { get; set; }
I have an issue. jQuery validation says that I have to enter date if I try '01.01.2001'.
Here is view
<div class="ElementDiv">
#Html.LabelFor(m => m.Filter.PeriodBeginFrom, new { #class = "Labels" })
#Html.EditorFor(m => m.Filter.PeriodBeginFrom, new { #class = "TextBoxes" })
#Html.ValidationMessageFor(m => m.Filter.PeriodBeginFrom, null, new { #class = "Errors" })
</div>
Why? With all other separators it works. What a problem is with '.' separatior?
Update 1: It seems that validation does not work properly. If I have this attribute at my model
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? PeriodBeginFrom { get; set; }
and we pass DateTime object to model, it will be displayed at textbox with '.' like '12.12.2012' and not like I was waiting '12/12/2012'. Hope you'll give me some ideas.

You're looking at a date component. But remember that time components can include seconds and fractional seconds, with a period inbetween. Since dates and times are frequently combined, I would not be surprised if the period is being treated as a special character.
Update:
I went through the following documentation chain:
DisplayFormatAttribute.ApplyFormatInEditMode Property
DisplayFormatAttribute.DataFormatString Property
Formatting Types
Custom Date and Time Format Strings
I expected to see that the period character has a special meaning in the format string. Instead, the documentation doesn't specifically list the period character. That means it should fall in the categry of "Any other character", and therefore, "The character is copied to the result string unchanged."
However, I don't believe it. Fractional seconds occur in time components like 23:59:59.999, and I suspect there is undocumented special treatment of the period character.

Trouble with a format was not with ASP tags and fields but with unobtrusive validation jquery library. I had to overload unobtrusive JavaScript validation method for date for my date format. More details are here
MVC DateTime validation - UK Date format

Related

ASP.NET MVC DisplayFormat for Hour

I have the following TimeSpan variable in my Model class:
[DisplayFormat(DataFormatString = "{0:HH-mm}", ApplyFormatInEditMode = true)]
public TimeSpan StartingHour { get; set; }
But when I call it from my View I got the error:
#Html.DisplayFor(modelItem => item.StartingHour)
System.FormatException: Input string was not in a correct format.
The value of the variable is: "18:00:00".
What should be in my DisplayFormat initialization? And please keep "get hour and minute separately from the time" advices to yourself.
Try: DataFormatString = #"{0:hh\-mm}"
Try using:
DataFormatString ="{0:hh\\:mm}"
Thanks.

format datetime value in C#

i want to format date time value in this format ("yyyy/MM/dd")
below is the code, m using to do so
DateTime? date = DateTime.Now;
DateTime? formattedDate = Convert.ToDateTime(date.Value.ToString("yyyy/MM/dd"));
Console.WriteLine(formattedDate);
Console.ReadLine();
the code work fine but you can see in the above code that i have declared datetime variable as null which in reverse causing the problem
please suggest what i am doing wrong in the above code.
as i am getting the output as this 9/10/2012 12:00:00 AM
Thanks,
Aaman
The problem is that what you call formattedDate is actually yet another instance of a DateTime. There's no notion of format inside the native .NET DateTime structure. You can talk about formatting only when you convert it to a string:
DateTime date = DateTime.Now;
string formattedDate = date.ToString("yyyy/MM/dd"));
Console.WriteLine(formattedDate);
or if you want to use a nullable DateTime:
DateTime? date = DateTime.Now;
string formattedDate = date.Value.ToString("yyyy/MM/dd"));
Console.WriteLine(formattedDate);
But since your question is tagged with asp.net-mvc-3, there are other ways to format values. For example using the [DisplayFormat] attribute on your view model:
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]
public DateTime? Date { get; set; }
and in your view if you want to display the value of your view model:
#Html.DisplayFor(x => x.Date)
or if you want to generate an input field with properly formatted value:
#Html.EditorFor(x => x.Date)

Custom error message not working for DateTime validation in asp net mvc 3

I have a ViewModel with a String property and the following Data Annotation :
Edit to work with string
[DataType(DataType.Date, ErrorMessage="Not Working !!!")]
public String StringBirthDate1 { get; set; }
That's my view
#Html.EditorFor(model => model.StringBirthDate1 )
#Html.ValidationMessageFor(model => model.StringBirthDate1)
If I run my application and put an invalid Date like '---' or 29.02.1900 I don't get any validation error !
Ok I've given up trying to use built-in MVC tools for data validation !
I did a custom Validation Attribute :
public class ValidDateStringAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
DateTime dtout;
if (DateTime.TryParse(value.ToString(), out dtout ))
{
return true;
}
return false;
}
}
Here is my View Model decorated with the custom attribute :
[ValidDateString(ErrorMessage="Invalid date format")]
public String BirthDate1 { get; set; }
Works like a charm :-)
It seems to me, that [DataType(DataType.Date, ErrorMessage="Not Working !!!")] working when it attached to string property. Try to use:
[DataType(DataType.Date, ErrorMessage="Not Working !!!")]
puplic string StringBirthDate1{get;set;}
public DateTime BirthDate1
{
get{return DateTime.Parse(StringBirthDate1);}
set{StringBirthDate1 = value.ToString();}
}
I didn't like any of the solutions I found so I kept poking at possibilities until I came up with one I do like. I added a regular expression validator utilizing the regular expression from this article: http://answers.oreilly.com/topic/226-how-to-validate-traditional-date-formats-with-regular-expressions/
[Required(ErrorMessage = "Birthdate is required. [MM/DD/YYYY]")]
[RegularExpression(#"^([1-9]|0[1-9]|1[0-2])[- / .]([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])[- / .](1[9][0-9][0-9]|2[0][0-9][0-9])$", ErrorMessage = "Birthdate must be in MM/DD/YYYY format.")]
public Nullable<DateTime> Birthdate { get; set; }
The result is, if the field is blank I get the required error message and if anything is in the field, but it is not a valid date, I get the regular expression message.
I might add that it seems very silly that [DataType] doesn't accept an error message. I tried exactly like the original author of this thread. That would have been logical and intuitive.

How to show a custom error message for DisplayFormat attribute In Asp.Net MVC?

How to show a custom error message for
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
The code in my model is following,
[Display(Name = "When was that document issued?")]
[DataType(DataType.Date, ErrorMessageResourceName = "DocumentIssueDate_DataType",ErrorMessageResourceType = typeof(CustomErrorMessages))]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime? DocumentIssueDate { get; set; }
In my View when I enter 201 in the date textbox I get the following error message. How do I modify the error message below.
The value '201' is not valid for DocumentIssueDate.
After a lot of research I had no luck. The only solution was to use RegularExpression.
Instead of using:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
You can use:
[RegularExpression(#"^(3[01]|[12][0-9]|0[1-9])[-/](1[0-2]|0[1-9])[-/][0-9]{4}$", ErrorMessageResourceName = "Date Not Valid")]
The RegularExpression matches the date format dd/MM/yyyy.
regular still not test yes but you can search and edit if need
Try see answers Here. I think DisplayFormat designed not for validation, that is why you can not use it to check if entered string is valid.

Input with date format set from ViewModel and html class attribute

I am working with razor view engine in asp.net mvc3.
Now, I need an input for a DateTime which should display the value in a fixed format (say dd-MMM-yyyy). So I can do:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MMM-yyyy}")]
public DateTime StartDate { get; set; }
And in the view:
#Html.EditorFor(model => model.StartDate)
But I need to add a class in the input. Which I think is not possible in EditorFor.
So I could use
#Html.TextBoxFor(model => model.StartDate, new { #class = "Date" })
But the display format does not work in this case.
Model can be null. So,
#Html.TextBox("StartDate", string.Format("{0:dd-MMM-yyyy}", Model.StartDate))
will throw NullReferenceException.
ophelia's way is a quicker version of mine. But this way is useful if you're going to have a few date fields in your application. So this is the way i like to do it:
-> In your solution explorer, create a folder inside Shared called "EditorTemplates"
-> In there, add a new (not strongly typed) Partial View. Call it "DateTime".
-> Open this view, and remove any code in there, and throw the following code in there:
#model System.DateTime
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { #class = "date" /* + any other html attributes you want */ })
-> In your ViewModel, your date field should be like this:
[Display(Name = "My Date:"), DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime MyDate { get; set; }
-> In your main view, and any view you want to use a date field, you can just use EditorFor on the property, like so:
#Html.EditorFor(m => m.MyDate)
You can initialize the date field in your controller or set a default date in your viewmodel's constructor.
I use this and its works fine:
#Html.TextBox("ExpiryDate", String.Format("{0:ddd, dd MMM yyyy}", DateTime.Now), new { id = "expirydate" })
Hope this is what you mean/need :)

Resources