2

How to change the language for "The value 'some value' is not valid for 'some property'" validation error?

Can anyone help? I want to translate the error in the picture to Russian Error. I read much sites, try to use RegularExpression, but it doesn't help may be I don't correctly understand how to do that?

I need only translate the error, not need to change the culture.

In web.config:

<globalization culture="en" uiCulture="en" />

My entity with data annotations attributes:

public class Player
{
    /* Some other properties */

    [Required(ErrorMessage = "Укажите среднее количество блокшотов")]
    [Range(0, 10.0, ErrorMessage = "Недопустимое значение, до 10")]
    public float BlockPerGame { get; set; }

    /* Some other properties */
}

My View:

@using (Html.BeginForm())
{
    @Html.HiddenFor(m => m.Id)    
    <div class="box-form">

    /* Some other properties */

    <div class="text-style-roboto form-group">
        <label>Среднее количество блокшотов</label>
        @Html.TextBoxFor(m => m.BlockPerGame, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.BlockPerGame)
    </div>

    /* Some other properties */

    <div class="form-group">
        <button type="submit" class="button button-create" id="button-create">Добавить</button>

        @Html.ActionLink("Отмена", "Index", null, new { @class = "button button-cancel", id = "button-cancel" })
    </div>
</div>
}

And my Controller:

public class AdminController : Controller
{
    /*Some other methods*/
    [HttpPost]
    public async Task<ActionResult> Edit(Player player, string ChoosingTeam)
    {
        if (ModelState.IsValid)
        {
            if (ChoosingTeam != string.Empty)
            {
                try
                {
                    player.TeamId = int.Parse(ChoosingTeam);
                    await repository.SavePlayerAsync(player);
                    TempData["message"] = string.Format("Игрок {0} {1} сохранены", player.Name, player.Surname);

                    return RedirectToAction("Index");
                }
                catch (Exception exc)
                {
                    Console.WriteLine(exc.Message);
                }
            }
        }
        IEnumerable<SelectListItem> list = new SelectList(repository.Teams, "Id ", "Name");
        ViewBag.ChoosingTeamName = list;
        return View(player);
    }
}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • You are entering an invalid float number (you use ',' istead of '.' as a separator). What if you use string as data type with [RegularExpression] instead of float? In this way you can add your custom error message – Popa Andrei Dec 30 '18 at 14:11

1 Answers1

4

When you enter an invalid value for a property, if model binder cannot bind that value to the property, the model binder sets an error message for that property. It's different from data-annotations model validation. It's in fact model binder validation error.

Localizing or Changing Default Model Binding Error Messages

Model binding error messages are different from model validation messages. To customize or localize them, you need to create a global resource and register it in Application_Start for DefaultModelBinder.ResourceClassKey.

To do so, follow these steps:

  1. Go to Solution Explorer
  2. Right click on project → AddASP.NET Folder → Choose App_GlobalResources
  3. Right click on App_GlobalResources → Choose Add New Item
  4. Choose Resource File and set the name to ErrorMessages.resx
  5. In the resource fields, add the following keys and values and save the file:
    • PropertyValueInvalid: The value '{0}' is not valid for {1}.
    • PropertyValueRequired: A value is required.

Note: If you want to just customize the messages, you don't need any language-specific resource, just write custom messages in the ErrorMessages.resx and skip next step.

  1. If you want localization, for each culture, copy the resource file and paste it in the same folder and rename it to ErrorMessages.xx-XX.resx. Instead of xx-XX use the culture identifier, for example fa-IR for Persian language and enter translation for those messages, for example for ErrorMessages.fa-IR.resx:

    • PropertyValueInvalid: مقدار '{0}' برای '{1}' معتبر نمی باشد.
    • PropertyValueRequired: وارد کردن مقدار الزامی است.
  2. Open Global.asax and in Application_Start, paste the code:

    DefaultModelBinder.ResourceClassKey = "ErrorMessages";
    

ASP.NET CORE

For ASP.NET Core read this post: ASP.NET Core Model Binding Error Messages Localization.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • doesn't translate 1) i create ErrorMasseges.ru-RU.resx 2)Name: PropertyValueInvalid ; Value:Значение '{0}' записано не верно в {1}. Name: PropertyValueRequired; Value : Значение пропущено 3) in global.asax add DefaultModelBinder.ResourceClassKey = "ErrorMessages"; i have the same english error i try fa-IR it doesn't translate –  Dec 30 '18 at 15:34
  • Because the culture of your application is still neutral culture. For you, since I see you are using Russian error messages even for neutral culture, just use Russian messages in `ErrorMasseges.resx`. Forget about the `ErrorMasseges.ru-RU.resx`. – Reza Aghaei Dec 30 '18 at 15:36
  • Make sure you have created the resource file in `App_GlobalResources` and follow my previous comment. As far as I see you are not using localization for validation attributes, so a single resource file for neutral culture would be enough. – Reza Aghaei Dec 30 '18 at 15:41
  • My mistake sorry that's working, thank you so much!!! really help! i delete ru-Ru and it worked –  Dec 30 '18 at 15:42