ASP.NET MVC 2 Model Validation With Localization

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

This entry was posted on Wednesday, February 17th, 2010 at 1:35 pm and is filed under MVC. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

10 Responses to “ASP.NET MVC 2 Model Validation With Localization”

Richard Thorne April 16th, 2010 at 10:32 am

You forgot to close your code tag dude. :-)

SlimShaggy April 24th, 2010 at 12:35 pm

Your post is broken when viewed in IE8 and Opera10.

Mike April 24th, 2010 at 10:22 pm

@SlimShaggy: Woa Thanks! I was missing a ” > ” made a big mess! I should test more with different browsers!!!!

KDR June 25th, 2010 at 3:34 am

Nice, very helpful ! Just one thing, in French, “charactères” is “caractères”, “Courriel invalid” becomes “Courriel invalide”, “Champs requis” is “Champ requis”.

Ajay singh July 20th, 2010 at 10:00 am

dear it very good example

Gurdeep July 30th, 2010 at 8:08 am

Hey, nice post !

Was struggling to find answers on the same. Thanks :)

But how do I select resources dynamically? In the code, “typeof(Global)” declaratively points out to the Global.resx file. I need to do that from a drop-down list, though. Also, I have menu items in my page. Using -following- how do I set resources inside my view for menu items dynamically?

ViewData["Message"] = Resources.Global.Welcome;

Thanks.

Vlad February 25th, 2011 at 3:44 am

MVC is really more about using the right view for the right job. Putting everything in a resource file is extremely painful. It’s good to use resource files for small things, but for larger pages like your description pages, its better to have a view in each culture with a lot of content. For example using the following structure:
~/Views/en-US/Home/Index.aspx
~/Views/pt-BR/Home/Index.aspx
or this structure:
~/Views/Home/Index.en-US.aspx ~/Views/Home/Index.en-US.aspx

Tell me what you think about this approach in combining forces in globalization.
http://blog.oimae.com/2011/02/20/cultured-view-engine-for-mvc/

Mike February 25th, 2011 at 7:51 am

@Vlad – This is interesting.. usually most of the content is in a database so I never really thought of it this way.. I’ll definitely read your website!

asp.net, c#,javascript September 30th, 2011 at 1:38 am

asp.net, c#,javascript…

[...]ASP.NET MVC 2 Model Validation With Localization | MIKE[...]…

Leave a Reply