Skip to content

Commit 49a4da0

Browse files
authored
fix(ValidateForm): compatible with custom validation classes not end with Attribute (#5752)
* refactor: 重构代码提高代码可读性 * refactor: 兼容非 Attribute 结尾的验证规则 * test: 更新单元测试
1 parent 35a7511 commit 49a4da0

File tree

2 files changed

+60
-25
lines changed

2 files changed

+60
-25
lines changed

src/BootstrapBlazor/Components/ValidateForm/ValidateForm.razor.cs

Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -385,10 +385,6 @@ private void ValidateDataAnnotations(object? value, ValidationContext context, L
385385
var result = rule.GetValidationResult(value, context);
386386
if (result != null && result != ValidationResult.Success)
387387
{
388-
// 查找 resource 资源文件中的 ErrorMessage
389-
var ruleNameSpan = rule.GetType().Name.AsSpan();
390-
var index = ruleNameSpan.IndexOf(attributeSpan, StringComparison.OrdinalIgnoreCase);
391-
var ruleName = ruleNameSpan[..index];
392388
var find = false;
393389
if (!string.IsNullOrEmpty(rule.ErrorMessage))
394390
{
@@ -400,29 +396,36 @@ private void ValidateDataAnnotations(object? value, ValidationContext context, L
400396
}
401397
}
402398

403-
// 通过设置 ErrorMessage 检索
404-
if (!context.ObjectType.Assembly.IsDynamic && !find
405-
&& !string.IsNullOrEmpty(rule.ErrorMessage)
406-
&& LocalizerFactory.Create(context.ObjectType).TryGetLocalizerString(rule.ErrorMessage, out var msg))
399+
if (!context.ObjectType.Assembly.IsDynamic)
407400
{
408-
rule.ErrorMessage = msg;
409-
find = true;
410-
}
401+
if (!find && !string.IsNullOrEmpty(rule.ErrorMessage)
402+
&& LocalizerFactory.Create(context.ObjectType).TryGetLocalizerString(rule.ErrorMessage, out var msg))
403+
{
404+
// 通过设置 ErrorMessage 检索
405+
rule.ErrorMessage = msg;
406+
find = true;
407+
}
411408

412-
// 通过 Attribute 检索
413-
if (!rule.GetType().Assembly.IsDynamic && !find
414-
&& LocalizerFactory.Create(rule.GetType()).TryGetLocalizerString(nameof(rule.ErrorMessage), out msg))
415-
{
416-
rule.ErrorMessage = msg;
417-
find = true;
418-
}
409+
if (!find && LocalizerFactory.Create(rule.GetType()).TryGetLocalizerString(nameof(rule.ErrorMessage), out msg))
410+
{
411+
// 通过 Attribute 检索
412+
rule.ErrorMessage = msg;
413+
find = true;
414+
}
419415

420-
// 通过 字段.规则名称 检索
421-
if (!context.ObjectType.Assembly.IsDynamic && !find
422-
&& LocalizerFactory.Create(context.ObjectType).TryGetLocalizerString($"{memberName}.{ruleName.ToString()}", out msg))
423-
{
424-
rule.ErrorMessage = msg;
425-
find = true;
416+
if (!find)
417+
{
418+
// 通过 字段.规则名称 检索
419+
// 查找 resource 资源文件中的 ErrorMessage
420+
var ruleNameSpan = rule.GetType().Name.AsSpan();
421+
var index = ruleNameSpan.IndexOf(attributeSpan, StringComparison.OrdinalIgnoreCase);
422+
var ruleName = index == -1 ? ruleNameSpan[..] : ruleNameSpan[..index];
423+
if (LocalizerFactory.Create(context.ObjectType).TryGetLocalizerString($"{memberName}.{ruleName.ToString()}", out msg))
424+
{
425+
rule.ErrorMessage = msg;
426+
find = true;
427+
}
428+
}
426429
}
427430

428431
if (!find)

test/UnitTest/Components/ValidateFormTest.cs

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -566,6 +566,27 @@ public async Task Validate_Service_Ok()
566566
var msg = cut.FindComponent<MockInput<string>>().Instance.GetErrorMessage();
567567
Assert.Equal(HasServiceAttribute.Success, msg);
568568
}
569+
570+
[Fact]
571+
public async Task TestService_Ok()
572+
{
573+
// 自定义验证规则没有使用约定 Attribute 结尾单元测试
574+
var foo = new HasService();
575+
var cut = Context.RenderComponent<ValidateForm>(pb =>
576+
{
577+
pb.Add(a => a.Model, foo);
578+
pb.AddChildContent<MockInput<string>>(pb =>
579+
{
580+
pb.Add(a => a.Value, foo.Tag2);
581+
pb.Add(a => a.ValueExpression, Utility.GenerateValueExpression(foo, "Tag2", typeof(string)));
582+
pb.Add(a => a.ValidateRules, [new FormItemValidator(new TestValidateRule())]);
583+
});
584+
});
585+
var form = cut.Find("form");
586+
await cut.InvokeAsync(() => form.Submit());
587+
var msg = cut.FindComponent<MockInput<string>>().Instance.GetErrorMessage();
588+
Assert.Equal("Test", msg);
589+
}
569590

570591
[Fact]
571592
public async Task RequiredValidator_Ok()
@@ -726,7 +747,7 @@ public void ShowAllInvalidResult_Ok()
726747
private class HasServiceAttribute : ValidationAttribute
727748
{
728749
public const string Success = "Has Service";
729-
public const string Error = "No Service";
750+
private const string Error = "No Service";
730751

731752
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
732753
{
@@ -738,10 +759,21 @@ private class HasServiceAttribute : ValidationAttribute
738759
}
739760
}
740761

762+
private class TestValidateRule : ValidationAttribute
763+
{
764+
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
765+
{
766+
return new("Test");
767+
}
768+
}
769+
741770
private class HasService
742771
{
743772
[HasService]
744773
public string? Tag { get; set; }
774+
775+
[TestValidateRule]
776+
public string? Tag2 { get; set; }
745777
}
746778

747779
[MetadataType(typeof(DummyMetadata))]

0 commit comments

Comments
 (0)