Skip to content

Commit 1b25367

Browse files
committed
修复自定义必填验证【RequiredAttribute】通过后(返回 ValidationResult 集合为零时),RequiredValidator 在验证未出结果之前(结果必定为通过)本地化包含自定义内容的 ErrorMessage 且其内容中有不符合 string.Format 方法要求的内容(如:ErrorMessage = $"当前 {{{nameof(MenuType)}}} 的值必须要设置 {{0}} 。")时导致程序崩溃问题。
自定义验证方法会正确处理 {{{nameof(MenuType)}}} 自定义内容。
1 parent 44afc80 commit 1b25367

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

src/BootstrapBlazor/Validators/RequiredValidator.cs

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
using Microsoft.Extensions.Localization;
99
using System.Collections;
1010
using System.Globalization;
11+
using System.Security.AccessControl;
1112

1213
namespace BootstrapBlazor.Components;
1314

@@ -53,17 +54,15 @@ public override void Validate(object? propertyValue, ValidationContext context,
5354
ErrorMessage = l.Value;
5455
}
5556
}
56-
var errorMessage = GetLocalizerErrorMessage(context, LocalizerFactory, Options);
57-
var memberNames = string.IsNullOrEmpty(context.MemberName) ? null : new string[] { context.MemberName };
5857
if (propertyValue == null)
5958
{
60-
results.Add(new ValidationResult(errorMessage, memberNames));
59+
results.Add(CreateValidationResult(context));
6160
}
6261
else if (propertyValue is string val)
6362
{
6463
if (!AllowEmptyString && val == string.Empty)
6564
{
66-
results.Add(new ValidationResult(errorMessage, memberNames));
65+
results.Add(CreateValidationResult(context));
6766
}
6867
}
6968
else if (propertyValue is IEnumerable v)
@@ -72,14 +71,26 @@ public override void Validate(object? propertyValue, ValidationContext context,
7271
var valid = enumerator.MoveNext();
7372
if (!valid)
7473
{
75-
results.Add(new ValidationResult(errorMessage, memberNames));
74+
results.Add(CreateValidationResult(context));
7675
}
7776
}
7877
else if (propertyValue is DateTimeRangeValue dv && dv is { NullStart: null, NullEnd: null })
7978
{
80-
results.Add(new ValidationResult(errorMessage, memberNames));
79+
results.Add(CreateValidationResult(context));
8180
}
8281
}
82+
/// <summary>
83+
/// 生成错误提示信息。
84+
/// </summary>
85+
/// <param name="context"></param>
86+
/// <returns></returns>
87+
private ValidationResult CreateValidationResult(ValidationContext context)
88+
{
89+
var errorMessage = GetLocalizerErrorMessage(context, LocalizerFactory, Options);
90+
var memberNames = string.IsNullOrEmpty(context.MemberName) ? null : new string[] { context.MemberName };
91+
return new ValidationResult(errorMessage, memberNames);
92+
}
93+
8394

8495
/// <summary>
8596
/// 获得当前验证规则资源文件中 Key 格式

0 commit comments

Comments
 (0)