Showing posts with label NuGet. Show all posts
Showing posts with label NuGet. Show all posts

Validating Date with MVC Foolproof Validation on the client side

This is a quick tip for something that I just tried with an ASP.NET MVC app and that worked as expected.

I use MVC Foolproof Validation to complement the standard validators that come with ASP.NET MVC in the System.ComponentModel.DataAnnotations assembly. Foolproof has some awesome validators like:

[Is]
[EqualTo]
[NotEqualTo]
[GreaterThan]
[LessThan]
[GreaterThanOrEqualTo]
[LessThanOrEqualTo]
[RequiredIf] [RequiredIfNot] [RequiredIfTrue] [RequiredIfFalse] [RequiredIfEmpty] [RequiredIfNotEmpty] [RequiredIfRegExMatch] [RequiredIfNotRegExMatch]

You can get it through a NuGet package here.

Let’s say you have a form with a DateTime field called “Show Until” that is part of a Notice object. This property stores a date value that should be in the future obviously. It makes no sense to set a date in the past for this field. So the question is: how can you get client side validation for this field without the need of going to the server to compare the date the user entered with today’s date?

This is what this post will show you…

This is the model property decorated with the respective data annotation GreaterThanOrEqualTo:

[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Localization))]
[Display(Name = "ShowUntil", ResourceType = typeof(Localization))]
[GreaterThanOrEqualTo("Today", ErrorMessageResourceName = "GreaterThanOrEqualTo", ErrorMessageResourceType = typeof(Localization))]
public DateTime ShowUntil { get; set; }

Pay attention to that "Today", string value. It tells Foolproof’s validator to compare the ShowUntil property with a property called Today (the dependent property). Wait a moment: the Notice object doesn’t have a property called Today since it’s not necessary. What’s the point? Confused smile

Now let’s add a partial class to extend the Notice class with a property called Today. This property returns Today’s date of course.

public partial class Notice
{
    public DateTime Today
    {
        get { return DateTime.Today; }
    }
}

Run the app now, enter a date in the past for the ShowUntil field and submit the form. You’ll see that a postback is made to the server and only after that the validation error message is shown to the user. Foolproof’s validator doesn’t know what’s the value of Today yet since it’s not part of the form data being edited. Remember: this kind of server side validation is not what we want. We want client side validation. We don’t want this data round-trip to the server just to validate one field in the form. So, how to solve this? It’s pretty simple…

Inside your form view (.cshtml file) since I’m using C# as the programming language and Razor view engine, add this hidden field:

@Html.HiddenFor(model => model.Today)

Now reload the page and try entering a date in the past like yesterday’s date. You’ll see that the user gets the validation error message instantly. Why? Because now Foolproof’s jQuery validator that is added to page has Today’s date value present in the form’s HTML output (that’s the purpose of the hidden field). If you look at the form/page source code in the browser (right click the browser window and select “View Page Source” in Firefox), you’ll se this value:

<input data-val="true" id="Today" name="Today" type="hidden" value="29/06/2012 00:00:00" />

That’s it. No date in the past is allowed when adding a new Notice to the system.

This use case can be considered a good use for Hidden fields. They serve a multitude of purposes…

Hope it helps.

Updated at 12:45 PM

You see how things are... after posting this I just discovered a really straightforward way of getting what I wanted (by chance) I can tell you. I wasn’t looking for this anymore when I hit this StackOverflow question. Looks like God took me there… Open-mouthed smile I happen to be using jQuery UI Datepicker control too. It has between its vast array of options a minDate property. So if you do this:

<script type="text/javascript">

    $(document).ready(function ()
    {
        $("#ShowUntil").datepicker('option', 'minDate', new Date());
    });

</script>

new Date() is Today in Javascript and so the datepicker won’t allow the selection of dates in the past. One word: AWESOME. One liner with jQuery help!

Export list of used NuGet packages for a given project

This one is as simple as the title says… I just wanted to get a list of all NuGet packages I’m currently using in my ASP.NET MVC 4 project.

If you look at the NuGet Package Manager window that you can access by right clicking a project in Solution Explorer and then selecting Manage NuGet Packages… you’ll see that there’s an Installed packages option on the left vertical menu. This is good and all but the manager doesn’t have an option to export the list of installed packages to a simple .txt file.

NuGet Package Manager listing Installed Packages for the projectFigure 1 - NuGet Package Manager listing Installed Packages for the project

One interesting thing is that NuGet uses a .XML file called packages.config that resides in the root folder of every project to actually fill the above window. Every time you add or delete a NuGet package this file is updated to reflect the changes.

This is the content of my packages.config file:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="AttributeRouting" version="1.5.4426" />
  <package id="DataAnnotationsExtensions" version="1.0.1" />
  <package id="DataAnnotationsExtensions.MVC3" version="1.0.1" />
  <package id="jQuery" version="1.7.1" />
  <package id="jQuery.Ajax.Unobtrusive" version="1.0" />
  <package id="jQuery.UI.Combined" version="1.8.17" />
  <package id="jQuery.Validation" version="1.8" />
  <package id="jQuery.Validation.Unobtrusive" version="1.0" />
  <package id="jquery-globalize" version="0.1.0" />
  <package id="knockoutjs" version="1.2.9.0" />
  <package id="log4net" version="1.2.10" />
  <package id="Microsoft.Web.Optimization" version="0.1" />
  <package id="microsoft-web-helpers" version="1.15" />
  <package id="Modernizr" version="2.0.6" />
  <package id="MvcSiteMapProvider" version="3.2.1.0" />
  <package id="Newtonsoft.Json" version="4.0.8" />
  <package id="NLog" version="2.0.0.2000" />
  <package id="RavenDB-Embedded" version="1.0.700" />
  <package id="System.Web.Providers" version="1.0.1" />
  <package id="T4MVC" version="2.7.0" />
  <package id="WebActivator" version="1.2.0.0" />
</packages>

This file serves the purpose of this post but it’d be a nice addition to the NuGet manager if it had a button to export the list of installed packages in a better formatted way. Just an idea.

Just let me take the opportunity to say “I Love You NuGet”. You let me explore the plethora of knowledge of fellow developers scattered all over the world in an easy way with the push of a button. I have no better words to describe you! You contribute enormously to the world development. Keep evolving!