JQuery Validation and MVC 3. How to change date format - asp.net-mvc-3

I'm a newbie to MVC 3 and JQuery Validation so any help I can get here will be very much appreciated.
My devleopment platform is .NET MVC 3 website. I'm using the built in unobtrusive javascript for form validation. Is there a way to change the date to a different format for a valid date. As far as I can tell, the valid format is dd/mm/yy. Is it possible to change the valid date format to something like "Apr 3, 2012"?
My view model has a field
[Required]
DateTime OrderDate { get; set; }
I know that MVC 3 is using jquery validation under the hood so I'm thinking the solution will require a change to jquery validate and also not sure how to hook it up to MVC so it works like all the other built in data validations using data annotations.
Thank you.

When you use client side validation for date, you have to override the jQuery validation for date as well.
$.validator.methods.date = function (value, element) {
return this.optional(element) || Globalize.parseDate(value, "MMM dd, yyyy") !== null;
}
You have to reference the Globalize library and the appropriate culture in your HTML head. Download from https://github.com/jquery/globalize.

If you wanted to change the format of Order Date you would do so with the DisplayFormat annotation:
[DisplayName("Order Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yy}")]
[Required]
DateTime OrderDate { get; set; }
Where the DataFormatString is your desired date time format.

Related

How to format date in partial view MVC

I am currently developing asp.net core(Framework 3.1) application. I am getting date from database and storing it in string(tried using DateTime but didn't work). Here's my code in model:
public string TranDate { get; set; }
salesList.Add(new SalesData()
{
TranDate = dt.Rows[i]["TRANDATE"].ToString(),
});
It displays date in "2020/06/06 00:00:00" format.
In partial view:
<td>
#Html.DisplayFor(modelItem => item.TranDate)
</td>
Now I want to display date in "dd/MM/yyyy" format like "06/06/2020" in my partial view. I have tried many ways like display templates, editor templates, String.Format but nothing works. Please help!
Please try something like the following;
string formattedDate = DateTime.Now.ToShortDateString(); //set a default date
if (DateTime.TryParse(TranDate, out DateTime usersDate))
{
formattedDate = usersDate.ToShortDateString();
}
TranDate = formattedDate;
Some of this may be too much, but the core premise is that using the DateTime.TryParse method ensures that the date being passed into it (your "TranDate" parameter) can even be converted to a date. I know it is coming from the database and likely a Date field itself, but we really should not trust that, to be sure.

How to validate date properly in mvc 3?

I want to validate the date properly.If Iam entering the date as 21-2-198 instead of 21-2-1988
.The date is not validating properly in Mvc3.I used Regex for this but didn't be useful.Is any other method to validate the date including the year in MVC model.Following is the code i written in the model
[Required(ErrorMessage = "Activation date is required")]
[Display(Name = "Activation date")]
[RegularExpression(#"/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d+$/", ErrorMessage = "Enter proper date")]
public DateTime? ActivationDate { get; set; }
you should be able to get validation by using the [DataType(DataType.Date)] attribute instead of your regular expression. Note that this Annotation is locale agnostic... i.e. 21-2-1988 and 2-21-1998 will both validate.
Iam entering the date as 21-2-198 instead of 21-2-1988 .The date is not validating properly in Mvc3.
It seems to me that you need a CustomValidator that prevents user to enter a date out of specific range.
ASP.NET MVC 3 Custom Validation using Data Annotations presents a Validator for this purpose.

ASP.NET MVC 4 avoid generation of data-val-date for datetime

how can I avoid the generation of the html attribute "data-val-date" for the element created from a Datetime property?
The model:
public class RegisterModel
{
[Required]
[Display(Name = "Date of birth")]
public DateTime? DateOfBirth { get; set; }
}
The view:
#Html.LabelFor(m => m.DateOfBirth)
#Html.EditorFor(m => m.DateOfBirth)
In fact, I'm creating a three drop down lists element for selecting the date of birth, which don't give a value in a date format.
Some solutions I've seen, consisted in a work around: removing the validation with a javascript.
The solution I envisage is to split the DateTime property into three long one for each value (day, month, year).
Ok, this took me an afternoon of work... apparently mvc4 decided that it was time to render a data-val-date="Message" on EVERY datetime property on the viewmodel. I've tried to modify this default behaviour but didn't succeed.
This solved my problems:
$.validator.addMethod('date',
function (value, element) {
return true; // since MVC4 data-val-date is put on EVERY vm date property. Default implementation does not allow for multiple cultures...
});
You can also try to write your own editor template named "DateTime.cshtml" in your shared EditorFor folder, but don't use TextBoxFor there, because that one is polluted as well.
data-val-date is used by the validation system to validate the date. If you remove it, client-side validation won't work.
If that's what you want, then just disable client-side validation.
Add this to your application start in your global.asax file and the form should fire.
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

Date Fails Client and Server Side Validation Using ASP.NET MVC 3 Data Annotations

In all my projects, I have jQuery date pickers that format the date dd-MMM-yyyy
which both users worldwide and the DateTime.parse method understand perfectly - sadly this does not appear to be the case for data annotation validation! I have my data annotation as below:
[Display(Name = "Date of Birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d-MMM-yyyy}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage = "You must enter a date of birth.")]
public DateTime dob { get; set; }
And my form refuses to submit with the error as below:
Does anyone know how I can make it validate, accept and modelbind a date value in this format?
You could write a custom model binder for the DateTime type as I have shown here that will use the format defined in the [DisplayFormat] attribute when parsing back a DateTime field from the request. By the default the model binder uses the CultureInfo setting of the current thread or the value you have configured in the <globalization> element of your web.config. If you set it to auto, then ASP.NET will use the client Accept-Language request header to adjust the culture info.

use other instead of #Html.DisplayFor in asp.net mvc 3 razor view

I am novice to the asp.net mvc3. It's really confusing and difficult to modify single code due to convention used in asp.net mvc3. I was trying to display only Date for BirthDate in the format 5 Sep 1999 instead which shows Date and Time.It's fine in Edit.cshtml, datepicker is used to pick the date and value is saved in database of only date. But, I have BirthDate column of Data type of Date not the DateTime and when using #Html.DisplayFor(model => model.BirthDate); in Details.cshtml shows both date and time. While Searching in google I have found and implement following code for displaying date in desire format:
#Model.BirthDate.ToString("dd MMM YYYY");
and
#Html.DisplayFor(model => model.BirthDate.ToString("dd MMM YYYY"));
It gives error no overload method takes 1 argument. Further I could use like:
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
pubilc DateTime BirthDate { get; set }
Since, I have used model first approach for Entity Framework. Where Should I implement above DisplayFormat property or what may be razor syntax to display date in right way in Details.csthml in my scenario
ok, I know I'm replying to a question posted 8 month before but my only intention is, this might be useful to others refering this question in future.
I'm also novoice to MVC and I also faced a similar problem where I need to display only the date and not the time and following worked for me.
Instead of #Html.DisplayFor(). Use <span>
So, for the case mentioned in question it would be like this:
<span>#String.Format("{0:D}", model.BirthDate)</span>
Output: Sunday, September 05, 1999
No, need to add extra class/file for formating.
The third approach is the best way according to me cos
your presentation model is dealing with all the aspects of UI and your view doesnt have unnecessary and redundant formatting code especially if you reuse the property.
enables unit testing
Consistent across different pages if you reuse the model.
You could also write an helper method that formats the date and use this consistently across all your presentation/view models.
public string FormattedDate(this DateTime dateTime)
{
return dateTime.ToString("dd MMM YYYY");
}
I like using a kind of decorator pattern to handle this kind of thing. Let's say your model class is called MyModel. Then define a wrapper class like this:
public class MyModelDecorator
{
public MyModel BaseItem { get; set; }
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime BirthDate { get; set; }
public MyModelDecorator(MyModel baseItem)
{
BaseItem = baseItem;
}
}
Then in your Views, you can refer to either the base model properties, or to the decorated properties.
#Html.DisplayFor(m => m.BirthDate)
#Html.DisplayFor(m => m.BaseItem.SomeOtherProperty)
If there's a better solution than this one, then I'd really like to hear it....
For any ASPX user sumbad answer helped but this is how you do it:
<%=Html.Enconde(String.Format("{0:D}", item.yourDate))%>
Hope this helps someone.

Resources