ASP.NET MVC 2 Model Validation With Localization

February 17th, 2010 / No Comments » / by Mike

So yesterday I posted about MVC 2 Model Validation. And today I’m going to do the same thing, but I’m going to Localize those ErrorMessage.

In this post I’ll not be using the SetCulture Attribute from ASP.NET MVC And Localization. Instead I’ll be using the auto-culture feature of ASP.NET which will be explained here; note you could achieve the same thing with the SetCulture Attribute.

Obviously, we’ll start by creating a new ASP.NET MVC 2 Web Application. I did not create a Test Project for this…

Then we need to setup proper Globalization configuration in our project. For this we’ll use the Auto-Culture features of ASP.NET. Open up the Web.Config and add this line.


    ....
    
        ....
        
    
    ....

Lets make sure the Globalization works.

First, we'll create the App_GlobalResources folder and add 2 resources files to it; Global.resx and Global.fr.resx. Also add some Resources to this files.

Well also need to make sure that these Resources files do not have Internal properties, but Public properties and also make it an embedded resources. To do this we need to click the Global.resx file, right-blick and go to properties. Set the Build Action to Embedded Resources and the Custom Tool to PublicResXFileCodeGenerator.

Now we'll change some hard-coded text to Resources. I simply opened up the HomeController and changed the Index action...

public ActionResult Index()
{
    ViewData["Message"] = Resources.Global.Welcome;

    return View();
}

Just try the application and make sure it works properly.

So now we know that our Localization works, but that's not what this post is about is it... What we want is to localize the Error Messages in our Model! So lets make a test model with some validation attributes!

Notice that I'm not using ErrorMessage anymore, instead I'm using ErrorMessageResourceType and ErrorMessageResourceName.

public class Test
{
    // StringLength
    [StringLength(5, ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "StringLength")]
    public string StringLength { get; set; }

    // Required
    [Required(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "Required")]
    public string Required { get; set; }

    // Required and StringLength
    [Required(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "Required")]
    [StringLength(5, ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "StringLength")]
    public string Combos { get; set; }

    // Range Attribute
    [Range(1, 31, ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "Range")]
    public int Range { get; set; }

    // RegularExpression Attribute
    [RegularExpression(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$", ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "Email")]
    public string Regex { get; set; }

    // Custom Regular Expression EmailAttribute
    [Email(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "Email")]
    public string Email { get; set; }
}

So that's it for the model, now we need a Controller and a View for that.

[HttpGet]
public ActionResult Create()
{
   var t = new Test();
   return View(t);
}

[HttpPost]
public ActionResult Create(Test t)
{
    if (ModelState.IsValid)
    {
        // If it's valid redirect to success page, or in my case the Home page since I have nothing else...
        return Redirect("/");
    }
    return View(t);
}

For the view, just right click on either Create and click Add View...

We don't need to change anything to the view so I'm not going to go into details on this one... Beside I'll post the Source Code when I'm done..

Here's the final result, with my browser set to French.

It's my first strike at this so if you have any comments or suggestion feel free to share it with us in the comment section!

Here's the Source Code

ASP.NET MVC 2 Model Validation

February 15th, 2010 / 4 Comments » / by Mike

In projects I usually work on, we always use a data validation framework. But now in ASP.NET MVC 2 you can do it just as you would using a framework.

You need to write your model with the proper validation attributes.

using System;
using System.ComponentModel.DataAnnotations;

namespace FunWithMvc2RC2
{
    public class Test
    {
        // StringLenght
        [StringLength(5, ErrorMessage = "Maximum 25 Characters")]
        public string StringLength { get; set; }

        // Required
        [Required(ErrorMessage = "Required Field")]
        public string Required { get; set; }

        // Required and StringLenght
        [Required(ErrorMessage = "Required Field")]
        [StringLength(5, ErrorMessage = "Maximum 25 Characters")]
        public string Combos { get; set; }

        // Range Attribute
        [Range(1, 31, ErrorMessage = "Minimum 1; Maximum 31")]
        public int Range { get; set; }

        // RegularExpression Attribute
        [RegularExpression(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$", ErrorMessage = "Invalid Email Address")]
        public string Regex { get; set; }

        // Custom Regular Expression EmailAttribute
        [Email(ErrorMessage = "Email Validation")]
        public string Email { get; set; }
    }
}

This will give you something like this:

And to make the Email Attribute you simply make a new class, which inherits RegularExpressionAttribute and then send the constructor an Email Address Regex! It’s this simple. You could do the same for any other Regular Expression based validation. Just Make sure you call your class – SomethingAttribute.

using System;
using System.ComponentModel.DataAnnotations;

namespace FunWithMvc2RC2
{
    public class EmailAttribute : RegularExpressionAttribute
    {
        public EmailAttribute() :
            base(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$") {}
    }
}

HOW TO: Turn Off Google Buzz

February 15th, 2010 / No Comments » / by Mike

If you’re like me and you don’t really like Google Buzz, know that you can easily turn it off by scrolling at the bottom of any page inside GMAIL.

Yeah, it’s that easy…