GibboK
GibboK

Reputation: 73928

MVC how to validate DateTime field with also client validation

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; }

Upvotes: 1

Views: 6528

Answers (2)

Rohit416
Rohit416

Reputation: 3486

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.

Upvotes: 3

Yasser Shaikh
Yasser Shaikh

Reputation: 47784

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 :

Upvotes: 1

Related Questions