在ViewModel中,我有一个像这样的属性:
[DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
public double SomeDoubleProperty { get; set; }
标记:
<div class="form-group row">
<label asp-for="ViewModel.SomeDoubleProperty" class="col-sm-3 col-form-label">
@Localizer[nameof(Model.ViewModel.SomeDoubleProperty)]
</label>
<div class="col-sm-9">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">%</span>
</div>
<input asp-for="ViewModel.SomeDoubleProperty"
class="form-control">
</div>
<span asp-validation-for="ViewModel.SomeDoubleProperty" class="text-danger"></span>
</div>
</div>
加载页面(默认值为0)后,它会在输入字段中显示如下:
(线程的当前区域性和当前ui文化是“ de”,因此十进制分隔符“,”是预期的)。
但是当我现在离开输入字段时,显示以下验证错误:
SomeDoubleProperty字段必须是数字。
将“,”替换为“。”时,验证器接受该值。 如果当前的ui文化是“ de”,我如何才能实现也接受“,”?
答案 0 :(得分:1)
您需要下载并配置客户端验证脚本:
在项目的根目录中,创建一个名为“ libman.json”的新文件,并将以下库添加到其中:
{
"version": "1.0",
"defaultProvider": "jsdelivr",
"libraries": [
{
"library": "cldrjs@0.5.1",
"destination": "wwwroot/lib/cldr"
},
{
"library": "cldr-data@35.1.0",
"destination": "wwwroot/lib/cldr-data"
},
{
"library": "globalize@1.4.2",
"destination": "wwwroot/lib/globalize"
}
]
}
保存文件后,它将所有脚本下载到wwwroor / lib文件夹。
然后打开wwwroot/lib/cldr-data/package.json
并将以下行添加到页面结尾处的结尾处:
"peerDependencies": {
"cldr-data": ">=26"
}
保存文件时,它将下载所有区域性的所有json数据(编号,日期,时间,货币等)。下载可能需要一段时间(〜35MB)。
还有一个js库“ jquery.validate.globalize.min.js”需要安装,但是jsdelivr 0.1.1中的版本不兼容,我们需要v1.0,因此可以从{{ 3}},或仅使用GitHub中的jsdelivr的导入功能,如下所示:
<script src="https://cdn.jsdelivr.net/gh/johnnyreilly/jquery-validation-globalize@1.0.0/jquery.validate.globalize.min.js"></script>
然后创建一个新的局部视图,名称为“ _LocalizationValidationScriptsPartial.cshtml”,并将库添加到其中:
<!-- cldr scripts (needed for globalize) -->
<script src="/lib/cldr/dist/cldr.min.js"></script>
<script src="/lib/cldr/dist/cldr/event.min.js"></script>
<script src="/lib/cldr/dist/cldr/supplemental.min.js"></script>
<!-- globalize scripts -->
<script src="/lib/globalize/dist/globalize.min.js"></script>
<script src="/lib/globalize/dist/globalize/number.min.js"></script>
<script src="/lib/globalize/dist/globalize/date.min.js"></script>
<script src="/lib/globalize/dist/globalize/currency.min.js"></script>
<!-- this file can be downloaded from : -->
<!-- https://github.com/johnnyreilly/jquery-validation-globalize -->
<script src="https://cdn.jsdelivr.net/gh/johnnyreilly/jquery-validation-globalize@1.0.0/jquery.validate.globalize.min.js"></script>
<!-- code to get check if current cultures scripts are exists -->
<!-- if not, select parent cultures scripts -->
@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment HostingEnvironment
@{
string GetDefaultLocale()
{
const string localePattern = "lib\\cldr-data\\main\\{0}";
var currentCulture = System.Globalization.CultureInfo.CurrentCulture;
var cultureToUse = "en"; //Default regionalisation to use
if (System.IO.Directory.Exists(System.IO.Path.Combine(HostingEnvironment.WebRootPath, string.Format(localePattern, currentCulture.Name))))
cultureToUse = currentCulture.Name;
else if (System.IO.Directory.Exists(System.IO.Path.Combine(HostingEnvironment.WebRootPath, string.Format(localePattern, currentCulture.TwoLetterISOLanguageName))))
cultureToUse = currentCulture.TwoLetterISOLanguageName;
return cultureToUse;
}
}
<script type="text/javascript">
var culture = "@GetDefaultLocale()";
$.when(
$.get("/lib/cldr-data/supplemental/likelySubtags.json"),
$.get("/lib/cldr-data/main/" + culture + "numbers.json"),
$.get("/lib/cldr-data/main/" + culture + "/currencies.json"),
$.get("/lib/cldr-data/supplemental/numberingSystems.json"),
$.get("/lib/cldr-data/main/" + culture + "/ca-gregorian.json"),
$.get("/lib/cldr-data/main/" + culture + "/timeZoneNames.json"),
$.get("/lib/cldr-data/supplemental/timeData.json"),
$.get("/lib/cldr-data/supplemental/weekData.json"),
).then(function () {
// Normalize $.get results, we only need the JSON, not the request statuses.
return [].slice.apply(arguments, [0]).map(function (result) {
return result[0];
});
}).then(Globalize.load).then(function () {
Globalize.locale(culture);
});
</script>
最后,只需在默认_ValidationScriptsPartial.cshtml之后添加此局部视图,即可完成本地化验证。
<partial name="_ValidationScriptsPartial.cshtml" />
<partial name="_LocalizationValidationScriptsPartial.cshtml" />
我创建了一个TagHelperComponent来避免进行所有繁琐的工作,甚至不需要将脚本下载到本地。
Install-Package LazZiya.TagHelpers -Version 2.1.0
@using LazZiya.TagHelpers
@addTagHelper *, LazZiya.TagHelpers
services.AddTransient<ITagHelperComponent, LocalizationValidationScriptsTagHelperComponent>();
<partial name="_ValidationScriptsPartial.cshtml" />
<localization-validation-scripts></localization-validation-scripts>
此TagHelper将自动检测当前的区域性名称,并添加用于验证本地化值的所有必需脚本。
有关更多详细信息,请参见GitHub
答案 1 :(得分:0)
由于@Laz Ziya,我找到了一个可以解决问题的组合:
ViewModel:
[DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
[Range(0, 100, ErrorMessage = "RangeAttribute_ValidationError")]
public double SomeDoubleProperty { get; set; }
标记:
<div class="form-group row">
<label asp-for="ViewModel.SomeDoubleProperty" class="col-sm-3 col-form-label">
@Localizer[nameof(Model.ViewModel.SomeDoubleProperty)]
</label>
<div class="col-sm-9">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">%</span>
</div>
<input asp-for="ViewModel.SomeDoubleProperty"
class="form-control"
id="some-double-input" digit-count="2">
</div>
<span asp-validation-for="ViewModel.SomeDoubleProperty" class="text-danger"></span>
</div>
</div>
<partial name="_NumberInputPartial" />
NumberInputPartial:
@using System.Threading;
@*To use this partial add the following attribute to the input element: digit-count="{enter requested digit count here}"*@
<script asp-location="Footer">
function toLocalizedNumberString(numberAsString, digitCount) {
var decimalSeparator = '@(Thread.CurrentThread.CurrentUICulture.NumberFormat.NumberDecimalSeparator)';
var groupSeparator = '@(Thread.CurrentThread.CurrentUICulture.NumberFormat.NumberGroupSeparator)';
var num = parseFloat(numberAsString.replace(decimalSeparator, '.'));
return ( num
.toFixed(digitCount)
.replace('.', decimalSeparator)
.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + groupSeparator)
)
}
$("input[digit-count]").on("focusin", function () {
$(this).val($(this).val().replace(@("/[" + Thread.CurrentThread.CurrentUICulture.NumberFormat.NumberGroupSeparator + "]/g"), ""));
});
$("input[digit-count]").on("focusout", function () {
$(this).val(toLocalizedNumberString($(this).val(), $(this).attr("digit-count")));
});
</script>
<partial name="_ValidationScriptsPartial" />
<localization-validation-scripts></localization-validation-scripts>