I want to use Data Annotations to validate DateTime fields, but I'm running into problems. According to documentation on MSDN (http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.rangeattribute.aspx), the following should do the job
[Range(typeof(DateTime), "1/2/2004", "3/4/2004",
ErrorMessage = "Value for {0} must be between {1} and {2}")]
However, this marks any date I enter as invalid!
At first I thought it was not picking up UK dates (when I tried 26/2/2004) but I can't even get it to use dates such as 2/2/2004.
I'm using the dataannotations within MVC2, and using the MicrosoftAjax framework for clientside validation.
Any suggestions?
Thanks
Well, a few years have gone past and I revisited this same issue with MVC4 and I can tell you that it has apparently been resolved.
I created a very simple default MVC4 site, and gave a date member the following attributes
[Required]
[DataType(DataType.Date)]
[Range(typeof(DateTime), "1/2/2004", "3/4/2004", ErrorMessage = "Value for {0} must be between {1} and {2}")]
public DateTime BlogDate { get; set; }
The validation now works perfectly under UK data system, disallowing a date 2/1/2004, allowing a date of 4/3/2004 or 26/3/2004.
The template I was using took advantage of code-first EF4, but I don't have any reason to suspect that it hasn't been fixed generally, since the javascript is working properly too.
So if you are using MVC2 this may still be a problem, but the best solution which I've found is to use MVC4 as long as it is available to you.
As far as i know the RangeAttribute can only validate number on client side, you'll have to write a custom javascript validator for this to work...
check out http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx for an example on how to do this.
Related
I'm having a terrible time adding a date to a view. I want the user to be able to type in a date like 6/30/15 or 6/30/2015, but the validation keeps failing if I use the 2 digit date. I've tried to "tell" MVC to accept a two digit date, but it always fails. Can someone explain how to get this right?
My view is set up like this (including just the troublesome date field for brevity):
#model Models.CompanyContracts
#Html.EditorFor(m => m.BegDate)
I started out with a simple model with a date field defined like this:
public DateTime? BegDate { get; set; }
I got an error saying "The field BegDate must be a date" when I entered the date as 6/30/15 or 06/30/15; I did not get the error when I entered 6/30/2015 or 06/30/2015.
So I tried to add a type and display attribute as describe
Here: Format datetime in asp.net mvc 4
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:M/d/yy}", ApplyFormatInEditMode = true)]
I get the same error trying to enter 6/30/15. I tried several different formats, including a datatype and not a displayformat, including a displayformat and not a datatype, but I get the "The field BegDate must be a date" error everytime.
I tried a regular expression validation and it also failed (both the MVC validation and the regular expression; obviously the regex I got from http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&categoryId=5&AspxAutoDetectCookieSupport=1 needs some work):
[RegularExpression(#"^((0?[13578]|10|12)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[01]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1}))|(0?[2469]|11)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[0]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1})))$", ErrorMessage = "Invalid Date")]
public DateTime? BegDate { get; set; }
Can someone tell me how to get MVC to accept entering dates with 2 or 4 digits?
One other note, no external date pickers. I need to get this working with a simple entering of text. Once I can prove that can be done, my boss might allow me to spend some time figuring out a date picker. Thanks!
-- Update 7/20/15 --
Anyone have suggestions for this? I haven't found anything online that's helped me. I'd appreciate any feedback at this point to give me somewhere else to look for a solution.
-- Update 7/29/15 --
Still looking for suggestions. Any ideas at all?
I think it's simply not possible without some kind of twist.
How is the engine/code suppose to know which year it is if you enter just 15 as the year.
Is it 2015 ? 1915 ? 2115 ?
You need to pass the 4 digits to create the dates, if you only have 2 digits you cannot create the date.
So in your case what I would try is to default and hide the '20' prefix (assuming you can only enter a date for 2000's) to your 2 digits year input (or add it somehow using a bit a javascript).
If I have a property in a view model like:
[DataType(DataType.DateTime)]
public DateTime? MyDate{ get; set; }
And a validation rule like this:
public class YourDetailsViewModelValidator : AbstractValidator<YourDetailsViewModel>
{
public YourDetailsViewModelValidator()
{
RuleFor(x => x.MyDate)
.InclusiveBetween(startDate, endDate)
.WithMessage("error");
}
}
Why does the error fire regardless of what date is input?
I did see a similar thing was happening enter link description herebut the answer was ultimately accepted so I'm hoping it can be made to work properly.
Error can be explained by difference in jquery.validate plugin date formatting and MVC helpers formatting. Just look in html generated by your view, and use
[DisplayFormat(DataFormatString="...")] // format string instead of dots
to make data-val-min and data-val-max attributes conform input value format (if they not, of course).
If value and validation attributes format are the same, but validation still fails - make sure that jquery.validate has appropriate format. In this case you should change ASP.NET MVC application culture to conform jquery.validate format, or vice versa — change jquery.validate format to conform application.
Similar questions asked on SO:
First
Second
.NET date formatting options available here.
I want do have my DateTime get displayed without the time.
So I use
item.AD_Date.Date
to cut off the time.
In the Model ( I use MVC) AD_Date is set up like this:
public System.DateTime AD_Date { get; set; }
But I get my date like this:
01.03.2013 00:00:00
What did I do wrong?
The Date property just returns a DateTime with the same date, but at midnight. There's no difference between "a DateTime at midnight" and "a DateTime just representing a date" (unfortunately).
You need to change how your DateTime is formatted to only show the date - either by annotating the model or by changing the view.
(Alternatively, use my Noda Time library which has different types for the different kinds of data you want to represent. I haven't tried using it with MVC, but at least for the formatting side it should work okay...)
If someone is facing the same problem, here is my formatting :
#String.Format("{0:yyyy-MM-dd}", item.AD_Date)
I am using Entity Framework 4 to provide the model for a ASP.NET MVC3 / Razor2 web application. I am using DataAnnotations to implement validation. I need to limit some dates to the range accepted by the SQL smalldatetime type.
My problem is that I can't get the RangeAttribute to work correctly for a date field. The model metadata definition for the field in question is:
[Display(ResourceType = typeof(Resources.Patient), Name = "DateOfBirth_Name")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
[Range(typeof(DateTime), "01/01/1900", "06/06/2079", ErrorMessageResourceType = typeof(Resources.Patient), ErrorMessageResourceName = "DateOfBirth_Range")]
public System.DateTime DateOfBirth { get; set; }
With this code, whatever value I put into the date field, it is treated as invalid by the application. In case its' relevant, I am using the JQuery-UI date picker with the field in question as well.
Can anyone help please?
You do not specify where the error occurs, but my guess is that it is client-side(?) jQuery Validation does not work well with the RangeAttribute. To verify, disable jQuery Validation and the valid input should pass the (server) validation.
To get around this you will have to write your own date range validation, e.g. http://blogs.msdn.com/b/stuartleeks/archive/2011/01/25/asp-net-mvc-3-integrating-with-the-jquery-ui-date-picker-and-adding-a-jquery-validate-date-range-validator.aspx
Alternatively you could look into packages such as Data Annotations Extensions or MVC Foolproof Validation to see if they could be used for solving the problem.
my object has field with data type int. when i put in html form in this textbox letter not number the validator say- The field must be a number. how can i change this messages like this
[Required(ErrorMessage = "Введите название")]
[DisplayName("Название")]
public int age { get; set; }
I haven't found a clean way to achieve this using Data Annotations. One way would be to write a custom model binder but this seems like a lot of work to do for such a simple task.
Another way to achieve this is to add an App_GlobalResources folder to your ASP.NET application. Add a resource file called Messages.resx containing a PropertyValueRequired string resource.
PropertyValueRequired = "Some custom error message"
In your Application_Start register the resource class key:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
DefaultModelBinder.ResourceClassKey = "Messages";
}
Note that ASP.NET MVC 2 uses the PropertyValueInvalid instead of PropertyValueRequired resource key.
IMO using Data Annotations to perform validation logic is limited (maybe in .NET 4 this will change). If you want to have full control over the validation logic I would recommend you using a validation library such as Fluent Validation or xVal.
I ran into the same problem and worked around it by specifying a RegularExpression that only allows positive natural numbers.
[Required(ErrorMessage = "Введите название")]
[DisplayName("Название")]
[RegularExpression(#"^[0-9]+$", ErrorMessage = "Поле возраст не является числом")]
public int age { get; set; }
Not sure if there are any downfalls to this solution. It seems to work fine for me.
PS: If you don't want to allow leading zeroes use "^[1-9]+[0-9]*$".
In retrospect: I have to admit though it's a bit weird to add a regular expression to an integer.