Monday, 15 April 2013

c# - MVC Validation message internationalization -



c# - MVC Validation message internationalization -

for example, default asp.net mvc 4 validation message: the value 'qsdqsdqs' not valid montant displayed in french.

i found bundle http://nuget.org/packages/microsoft.aspnet.mvc.fr/ , installed how work ?

i added <globalization culture="fr-fr" uiculture="auto:fr" /> web.config , referenced dll message still in english

first of should maintain messages in resources files that:

resources/errormessages.resx // default messages resources/errormessages.fr.resx // french

on server side it's vary easy, , can adding attribute model. that:

[required(errormessageresourcetype = typeof(resources.errormessages), errormessageresourcename = "fieldrequired")]

where "fieldrequired" 1 of fields in resources.errormessages

the tricky part when want client side validation work well. have create own attribute class extends 1 of attributes , implements iclientvalidatable.

you that:

public class customrequiredattribute : requiredattribute, iclientvalidatable { public override string formaterrormessage(string name) { homecoming string.format(errormessages.fieldrequired, name); } public ienumerable<modelclientvalidationrule> getclientvalidationrules(modelmetadata metadata, controllercontext context) { var rule = new modelclientvalidationrequiredrule(string.format(errormessages.fieldrequired, metadata.displayname)); homecoming new[] { rule }; } }

from on utilize customrequired instead of required in models. don't have specify message each time.

edit

now i've seen comment on synercoder's reply - don't want translate messages yourself. don't think it's right approach. if find translate standard messages won't translate custom messages, you'll end mixing 2 approaches. leads magic errors don't know how bite. suggest translations (it's not much - 20 or so?). benefit flexible solution no unexpected errors.

c# validation asp.net-mvc-4 internationalization

No comments:

Post a Comment