如何在blazor服务器端本地化验证消息(DataAnnotationsValidator) [英] How to Localize validation message (DataAnnotationsValidator) in blazor server side

查看:233
本文介绍了如何在blazor服务器端本地化验证消息(DataAnnotationsValidator)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在最新版本的VS 2019中使用blazor 3.1.

到目前为止,我已经能够本地化页面标签(标题,表格字段等).

ListEmployee.razor 页面上,我能够本地化表格标题等.在 AddEmplyeeValidation.razor 页面上,我能够本地化表单标签,但是我有本地化验证消息时出现问题.

对于 Employee.cs 文件的验证消息,验证消息在 Data.Employee.resx Resources/Data 文件夹中定义.>和 Data.Employee.ar.resx ,但这似乎不起作用.

使用System.ComponentModel.DataAnnotations

 命名空间BlazorSPA1.Data{公职员工{[MaxLength(50)]公共字符串ID {get;放;}[必需(ErrorMessage =名称为RR必需"))[StringLength(20,ErrorMessage =名称太长.")公共字符串名称{get;放;}[必需的][StringLength(20)]公共字符串部{放;}[MaxLength(100)]公共字符串名称{放;}[MaxLength(100)]公开字符串公司{放;}[MaxLength(100)]公共字符串City {get;放;}}} 

如何根据我的 AddEmployeForm 的语言从资源文件中加载验证消息?

  @page"/addemployeeValidation"@inject NavigationManager导航管理器@inject IEmployeeService EmployeeService@inject IStringLocalizer< AddEmployeeValidation>大号< h2>创建员工</h2>< hr/>< EditForm模型="@ employee" OnValidSubmit ="@ CreateEmployee">< DataAnnotationsValidator/>< ValidationSummary/>< div class ="row">< div class ="col-md-8">< div class ="form-group">< label for ="Name" class ="control-label"&@; L ["Name"]</label>< input for ="Name" class ="form-control" @bind ="@ employee.Name"/>< ValidationMessage For ="@(()=> employee.Name)"/></div>< div class ="form-group">< label for =部门" class ="control-label"&@@ L [部门"]</label>< input for =部门" class ="form-control" @bind ="@ employee.部门"/></div>< div class ="form-group">< label for ="Designation" class ="control-label"&@@ L ["Designation"]</label>< input for ="Designation" class ="form-control" @bind ="@ employee.Designation"/></div>< div class ="form-group">< label for ="Company" class ="control-label"&@@ L ["Company"]</label>< input for ="Company" class ="form-control" @bind ="@ employee.Company"/></div>< div class ="form-group">< label for ="City" class ="control-label"&@@ L ["City"]</label>< input for ="City" class ="form-control" @bind ="@ employee.City"/></div></div></div>< div class ="row">< div class ="col-md-4">< div class ="form-group">< input type ="submit" class ="btn btn-primary" value =保存"/>< input type ="button" class ="btn" @onclick ="@ Cancel" value ="Cancel"/></div></div></div></EditForm>@代码 {Employee员工= new Employee();受保护的异步任务CreateEmployee(){等待EmployeeService.CreateEmployee(employee);NavigationManager.NavigateTo("listemployees");}无效Cancel(){NavigationManager.NavigateTo("listemployees");}} 

我已经阅读了几篇文章,并尝试了一些尝试,但似乎没有任何效果.

这是我的 Startup.cs 代码:

 服务.AddServerSideBlazor(options => options.DetailedErrors = true);services.AddLocalization(options => options.ResourcesPath =资源");varsupportedCultures = new List< CultureInfo>{new CultureInfo("en"),new CultureInfo("ar")};services.Configure< RequestLocalizationOptions>(options =>{options.DefaultRequestCulture =新的Microsoft.AspNetCore.Localization.RequestCulture("en");options.SupportedUICultures = supportCultures;}); 

我使用以下示例进行本地化,但未显示如何本地化错误消息:

英语版本的资源文件示例以同样的方式我也有阿拉伯文件:

在下面的屏幕截图中,您将看到字段名称已从资源文件中正确提取,但是验证消息不起作用,仅以英文显示.

解决方案

这是我用于本地化数据注释错误消息的解决方案.我创建了两个资源文件,一个用于字段,另一个用于错误消息.

  • DisplayNameResource 用于本地化字段
  • ErrorMessageResource 用于本地化错误消息

在视图模型类中,使用 Display 属性本地化字段名称.要指定资源文件,请使用 Display 属性上的 ResourceType 属性:

  [Display(Name ="Address",ResourceType = typeof(DisplayNameResource))] 

在验证属性上,使用 ErrorMessageResourceName ErrorMessageResourceType 指定资源文件:

  [Required(ErrorMessageResourceName ="RequiredError",ErrorMessageResourceType = typeof(ErrorMessageResource))] 

以下是完整示例:

 公共类SomeViewModel{[Display(名称=地址",ResourceType = typeof(DisplayNameResource))][Required(ErrorMessageResourceName ="RequiredError",ErrorMessageResourceType = typeof(ErrorMessageResource))][StringLength(256,ErrorMessageResourceName ="MaxLengthError",ErrorMessageResourceType = typeof(ErrorMessageResource))]公共字符串地址{get;放;}[Display(名称=电话",ResourceType = typeof(DisplayNameResource))][Required(ErrorMessageResourceName ="RequiredError",ErrorMessageResourceType = typeof(ErrorMessageResource))][RegularExpression("^ 09([0-9] {9})$",ErrorMessageResourceName ="PhoneLengthError",ErrorMessageResourceType = typeof(ErrorMessageResource))]公共字符串Phone {get;放;}[Display(名称=密码",ResourceType = typeof(DisplayNameResource))][Required(ErrorMessageResourceName ="RequiredError",ErrorMessageResourceType = typeof(ErrorMessageResource))][StringLength(50,MinimumLength = 6,ErrorMessageResourceType = typeof(ErrorMessageResource),ErrorMessageResourceName ="MinxMaxLengthError")]公共字符串密码{get;放;}[Display(名称="ConfirmPassword",ResourceType = typeof(DisplayNameResource))][Required(ErrorMessageResourceName ="RequiredError",ErrorMessageResourceType = typeof(ErrorMessageResource))][StringLength(50,MinimumLength = 6,ErrorMessageResourceType = typeof(ErrorMessageResource),ErrorMessageResourceName ="MinxMaxLengthError")][Compare("Password",ErrorMessageResourceName ="PasswordConfirmMisMatch",ErrorMessageResourceType = typeof(ErrorMessageResource))]公共字符串ConfirmPassword {get;放;}} 

MaxLengthError 的错误消息为 {0}不能超过{1}个字符,因此 {0} 将替换为本地化文件名和 {1} 将替换为您在属性 [StringLength(256,...

I am using blazor 3.1 in latest version of VS 2019.

So far, I am able to localize page labels (title, table fields etc.).

On the ListEmployee.razor page, I am able to localize table heading etc. On the AddEmplyeeValidation.razor page, I am able to localize form labels but I have a problem localizing the validation messages.

For validation message for the Employee.cs file, validation message are defined in the Resources/Data folder in files Data.Employee.resx and Data.Employee.ar.resx but this doesn't seem to work.

    using System.ComponentModel.DataAnnotations;

    namespace BlazorSPA1.Data
    {
        public class Employee
        {
            [MaxLength(50)]
            public string Id { get; set; }

            [Required (ErrorMessage ="Name is RRRequired")]
            [StringLength(20, ErrorMessage = "Name is too long.")]
            public string Name { get; set; }

            [Required]
            [StringLength(20)]
            public string Department { get; set; }
            [MaxLength(100)]
            public string Designation { get; set; }
            [MaxLength(100)]
            public string Company { get; set; }
            [MaxLength(100)]
            public string City { get; set; }
        }
    }

How can I load the validation messages from the resource files based on language for my AddEmployeForm?

    @page "/addemployeeValidation"
    @inject NavigationManager NavigationManager
    @inject IEmployeeService EmployeeService
    @inject IStringLocalizer<AddEmployeeValidation> L

    <h2>Create Employee</h2>
    <hr />
    <EditForm Model="@employee" OnValidSubmit="@CreateEmployee">
        <DataAnnotationsValidator />
        <ValidationSummary />
        <div class="row">
            <div class="col-md-8">
                <div class="form-group">
                    <label for="Name" class="control-label">@L["Name"]</label>
                    <input for="Name" class="form-control" @bind="@employee.Name" />
                    <ValidationMessage For="@(()=> employee.Name)" />
                </div>
                <div class="form-group">
                    <label for="Department" class="control-label">@L["Department"]</label>
                    <input for="Department" class="form-control" @bind="@employee.Department" />
                </div>
                <div class="form-group">
                    <label for="Designation" class="control-label">@L["Designation"]</label>
                    <input for="Designation" class="form-control" @bind="@employee.Designation" />
                </div>
                <div class="form-group">
                    <label for="Company" class="control-label">@L["Company"]</label>
                    <input for="Company" class="form-control" @bind="@employee.Company" />
                </div>
                <div class="form-group">
                    <label for="City" class="control-label">@L["City"]</label>
                    <input for="City" class="form-control" @bind="@employee.City" />
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-4">
                <div class="form-group">
                    <input type="submit" class="btn btn-primary" value="Save" />
                    <input type="button" class="btn" @onclick="@Cancel" value="Cancel" />
                </div>
            </div>
        </div>
    </EditForm>

    @code {

        Employee employee = new Employee();

        protected async Task CreateEmployee()
        {
            await EmployeeService.CreateEmployee(employee);
            NavigationManager.NavigateTo("listemployees");
        }


        void Cancel()
        {
            NavigationManager.NavigateTo("listemployees");
        }
    }   

I have read a few articles and tried few thing but nothing seems to be working.

Here is my Startup.cs code:

        services.AddServerSideBlazor(options => options.DetailedErrors = true);
        services.AddLocalization(options => options.ResourcesPath = "Resources");
        var supportedCultures = new List<CultureInfo> { new CultureInfo("en"), new CultureInfo("ar") };
        services.Configure<RequestLocalizationOptions>(options =>
        {
            options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en");
            options.SupportedUICultures = supportedCultures;
        });

I am using the following example for localization but it doesn't show how to localize error messages: https://www.c-sharpcorner.com/article/localization-in-blazor-server/

Folder structure image for reference:

Resource file example for English version in same way i have Arabic file also:

In the screenshot below, you will see field names are being pulled correctly from the Resource file but validation messages are not working and only display in English.

解决方案

Here is my solution for localizing data annotation error messages. I create two resource files, one for fields and another one for error messages.

  • DisplayNameResource for localizing fields
  • ErrorMessageResource for localizing error messages

In view model class use Display attribute for localizing field name. To specify resource file use ResourceType property on Display attribute:

[Display(Name = "Address", ResourceType = typeof(DisplayNameResource))]

And on validation attributes use ErrorMessageResourceName and ErrorMessageResourceType to specify resource file:

[Required(ErrorMessageResourceName = "RequiredError", ErrorMessageResourceType = typeof(ErrorMessageResource))]

Here is full example:

public class SomeViewModel
{
    [Display(Name = "Address", ResourceType = typeof(DisplayNameResource))]
    [Required(ErrorMessageResourceName = "RequiredError", ErrorMessageResourceType = typeof(ErrorMessageResource))]
    [StringLength(256, ErrorMessageResourceName = "MaxLengthError", ErrorMessageResourceType = typeof(ErrorMessageResource))]
    public string Address { get; set; }

    [Display(Name = "Phone", ResourceType = typeof(DisplayNameResource))]
    [Required(ErrorMessageResourceName = "RequiredError", ErrorMessageResourceType = typeof(ErrorMessageResource))]
    [RegularExpression("^09([0-9]{9})$", ErrorMessageResourceName = "PhoneLengthError", ErrorMessageResourceType = typeof(ErrorMessageResource))]
    public string Phone { get; set; }

    [Display(Name = "Password", ResourceType = typeof(DisplayNameResource))]
    [Required(ErrorMessageResourceName = "RequiredError", ErrorMessageResourceType = typeof(ErrorMessageResource))]
    [StringLength(50, MinimumLength = 6, ErrorMessageResourceType = typeof(ErrorMessageResource), ErrorMessageResourceName = "MinxMaxLengthError")]
    public string Password { get; set; }

    [Display(Name = "ConfirmPassword", ResourceType = typeof(DisplayNameResource))]
    [Required(ErrorMessageResourceName = "RequiredError", ErrorMessageResourceType = typeof(ErrorMessageResource))]
    [StringLength(50, MinimumLength = 6, ErrorMessageResourceType = typeof(ErrorMessageResource), ErrorMessageResourceName = "MinxMaxLengthError")]
    [Compare("Password", ErrorMessageResourceName = "PasswordConfirmMisMatch", ErrorMessageResourceType = typeof(ErrorMessageResource))]
    public string ConfirmPassword { get; set; }
}

Error message for MaxLengthError is {0} cannot be longer than {1} character, so {0} will be replaced with localized filed name and {1} will be replaced with the 256 you specified on attribute [StringLength(256,...

这篇关于如何在blazor服务器端本地化验证消息(DataAnnotationsValidator)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆