1

In my View Model I have setup a field with this attributes.

All work fine if the user enter the date and time in the correct format.

An error appear if the User do not insert the DateTime in the right format.

I would like have validation also in the client.

Could you tell me how to do it?

   [Required]
    [Display(Name = "Start DateTime")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy HH:mm}")]
    public System.DateTime DateTimeStart { get; set; }
1
  • So, it only checks DateTime on the server without first doing in on the client side when you submit an invalid value? Commented Jan 23, 2013 at 9:04

2 Answers 2

3

Getting format exceptions from a property of type DateTime is very annoying issue. It is a fairly common issue when working with validation on DateTime.

DataAnnotaions works on server side and to take their full advantage you need to add ModelState.IsValid() in your controller.

public ActionResult Index(MyViewModel model)
{
    if(ModelState.IsValid())
    {
       // valid data received...
    }
    else
    {
       // Invalid data, add model error here and return view...
    }
}

If you to make these work on client side then you need to include two additional JavaScript files in your code i.e. jquery.validate.js and jquery.validate.unobtrusive.js along with jQuery core library. By Default all of these files comes in basic MVC project and included in Layout.

It is important to note the order of including these files. jQuery core should always be at the top followed by validation libraries.

  • jquery.js
  • jquery.validate.js
  • jquery.validate.unobtrusive.js

Make sure the validation flags are turned on in web.config file of MVC project. Go to this file and locate the following and set them true if they are false.

<appSettings>
  <add key="ClientValidationEnabled" value="true"/> 
  <add key="UnobtrusiveJavaScriptEnabled" value="true"/> 
</appSettings>

This should setup your validations to work on client side. You can decorate the model property with the RegularExpression.

 [Required]
 [RegularExpression("^(([0-2]?[0-9]|3[0-1])/([0]?[1-9]|1[0-2])/[1-2]\d{3}) (20|21|22|23|[0-1]?\d{1}):([0-5]?\d{1})$", ErrorMessage = "Invalid date")]
 public string DateTimeStart { get; set; }

This will validate the datetime in dd-mm-yyyy hh:mm format.

Besides in this case you can make your property a string type also because regular expression will take care of your date format.

Apart from this, you can also create your custom DataAnnotation.

Sign up to request clarification or add additional context in comments.

9 Comments

"02/31/2013 00:00" how do you plan to handle this ? your regex will mark this date as valid, and this date is not valid.
i have never used such type of format, only dates so no fluke guesses.
if that is the case, jquery datepicker would be a good option :)
Thanks Razor the solution with Regular Expression seems suitable in my case, unfortunately I was not able to modify correctly your regular expression. Validation should pass if the entered value is in this format 01/23/2013 10:25
[RegularExpression("^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9][0-9]$", ErrorMessage = "Invalid date")] should help
|
1

Firstly, what are you using to allow user to enter a date ?

If you are using Jquery DatePicker, then see this example there is no way the user can enter date in wrong format (except for inspecting the element and changing the textbox value, which can be ignored.)

Sample Code using Jquery Datepicker :

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
  <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css" />
  <script>
  $(function() {
    $( "#datepicker" ).datepicker();
  });
  </script>
</head>
<body>

<p>Date: <input type="text" id="datepicker" /></p>


</body>
</html>

and incase you are not using DatePicker I very strongly recommend you to use it.

Incase you are new to datepicker, you can go through the following listed articles to get started :

4 Comments

User can enter the date in a simple Text Field, the use of a Date picker it is not required at the moment. Thanks for your answer.
This example of DataPicker dost not include the selection of HH and MM...anyway thanks for posting
if you are not using datepicker, you will have to do a LOT of validations, for example : 30/31 days in different months or is the current year a leap year for Feb to have 29 days... and so on.
Using the datepicker does not prevent you from typing in an invalid date. It will force you to enter numeric digits in the format of ##/##/####, but you can enter in any digits here. Ex: 44/44/4444.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.