Skip to content

Commit

Permalink
feat(RequiredValidator): enhance the RequiredValidator class (#4247)
Browse files Browse the repository at this point in the history
* refactor: 更改内部变量名

* refactor: 移除公共属性

* feat: 增加多语言支持

* chore: 更新字典表

* test: 更新单元测试名称

* test: 更新单元测试
  • Loading branch information
ArgoZhang authored Sep 10, 2024
1 parent 5369c28 commit b8c28d1
Show file tree
Hide file tree
Showing 8 changed files with 34 additions and 16 deletions.
1 change: 1 addition & 0 deletions exclusion.dic
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ Github
menuitem
Segmenteds
Responsives
resx
tabset
Splittings
Foos
Expand Down
13 changes: 7 additions & 6 deletions src/BootstrapBlazor/Components/Validate/ValidateBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,8 @@ protected virtual bool TryParseValueFromString(string value, [MaybeNullWhen(fals
/// <returns></returns>
protected virtual bool IsRequired() => ShowRequired ?? FieldIdentifier
?.Model.GetType().GetPropertyByName(FieldIdentifier.Value.FieldName)!.GetCustomAttribute<RequiredAttribute>(true) != null
|| (ValidateRules?.OfType<FormItemValidator>().Select(i => i.Validator).OfType<RequiredAttribute>().Any() ?? false);
|| (ValidateRules?.OfType<FormItemValidator>().Select(i => i.IsRequired).Any() ?? false)
|| (ValidateRules?.OfType<RequiredValidator>().Any() ?? false);

/// <summary>
/// Gets a string that indicates the status of the field being edited. This will include
Expand Down Expand Up @@ -295,7 +296,7 @@ protected override void OnParametersSet()

if (ShowRequired is true)
{
Rules.Add(new RequiredValidator() { ErrorMessage = RequiredErrorMessage ?? GetDefaultErrorMessage() });
Rules.Add(new RequiredValidator() { ErrorMessage = RequiredErrorMessage ?? GetDefaultRequiredErrorMessage() });
}
}

Expand All @@ -321,12 +322,12 @@ protected override async Task OnAfterRenderAsync(bool firstRender)
}
}

private string? _defaultErrorMessage;
private string? _defaultRequiredErrorMessage;

private string GetDefaultErrorMessage()
private string GetDefaultRequiredErrorMessage()
{
_defaultErrorMessage ??= Localizer["DefaultErrorMessage"];
return _defaultErrorMessage;
_defaultRequiredErrorMessage ??= Localizer["DefaultRequiredErrorMessage"];
return _defaultRequiredErrorMessage;
}

#region Validation
Expand Down
2 changes: 1 addition & 1 deletion src/BootstrapBlazor/Locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,6 @@
"LightModeText": "Light"
},
"BootstrapBlazor.Components.ValidateBase": {
"DefaultErrorMessage": "{0} is required."
"DefaultRequiredErrorMessage": "{0} is required."
}
}
2 changes: 1 addition & 1 deletion src/BootstrapBlazor/Locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,6 @@
"LightModeText": "明亮"
},
"BootstrapBlazor.Components.ValidateBase": {
"DefaultErrorMessage": "{0}是必填项"
"DefaultRequiredErrorMessage": "{0}是必填项"
}
}
12 changes: 6 additions & 6 deletions src/BootstrapBlazor/Validators/FormItemValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,6 @@ namespace BootstrapBlazor.Components;
/// <param name="attribute"></param>
public class FormItemValidator(ValidationAttribute attribute) : ValidatorBase
{
/// <summary>
/// 获得 ValidationAttribute 实例
/// </summary>
public ValidationAttribute Validator { get; } = attribute;

/// <summary>
/// 验证方法
/// </summary>
Expand All @@ -23,10 +18,15 @@ public class FormItemValidator(ValidationAttribute attribute) : ValidatorBase
/// <param name="results">ValidateResult 集合实例</param>
public override void Validate(object? propertyValue, ValidationContext context, List<ValidationResult> results)
{
var result = Validator.GetValidationResult(propertyValue, context);
var result = attribute.GetValidationResult(propertyValue, context);
if (result != null)
{
results.Add(result);
}
}

/// <summary>
/// 是否为 RequiredAttribute 标签特性
/// </summary>
public bool IsRequired => attribute is RequiredAttribute;
}
10 changes: 10 additions & 0 deletions src/BootstrapBlazor/Validators/RequiredValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using BootstrapBlazor.Localization.Json;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using System.Collections;
using System.Globalization;
Expand Down Expand Up @@ -43,6 +44,15 @@ public class RequiredValidator : ValidatorBase
/// <param name="results">ValidateResult 集合实例</param>
public override void Validate(object? propertyValue, ValidationContext context, List<ValidationResult> results)
{
if (string.IsNullOrEmpty(ErrorMessage))
{
var localizer = context.GetRequiredService<IStringLocalizer<ValidateBase<string>>>();
var l = localizer["DefaultRequiredErrorMessage"];
if (!l.ResourceNotFound)
{
ErrorMessage = l.Value;
}
}
var errorMessage = GetLocalizerErrorMessage(context, LocalizerFactory, Options);
var memberNames = string.IsNullOrEmpty(context.MemberName) ? null : new string[] { context.MemberName };
if (propertyValue == null)
Expand Down
2 changes: 1 addition & 1 deletion test/UnitTest/Components/ValidateFormTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ public async Task ValidateFromCode_Ok()
}

[Fact]
public async Task Validate_Servise_Ok()
public async Task Validate_Service_Ok()
{
var foo = new HasService();
var cut = Context.RenderComponent<ValidateForm>(pb =>
Expand Down
8 changes: 7 additions & 1 deletion test/UnitTest/Validators/RequiredValidatorTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public void AllowEmptyString_Ok()
}

[Fact]
public void EnnumerableValue_Ok()
public void EnumerableValue_Ok()
{
var foo = new Foo();
var validator = new RequiredValidator()
Expand Down Expand Up @@ -75,5 +75,11 @@ public void Localizer_Ok()
validator.Options.ResourceManagerStringLocalizerType = typeof(Foo);
validator.Validate("v1", context, results);
Assert.Empty(results);

var provider = Context.Services.GetRequiredService<IServiceProvider>();
validator = new RequiredValidator();
context = new ValidationContext(foo, provider, null);
validator.Validate(null, context, results);
Assert.Single(results);
}
}

0 comments on commit b8c28d1

Please sign in to comment.