Skip to content

Commit 286e9cf

Browse files
committed
refactor: 增加 GetRequiredValidator 扩展方法
1 parent 736a23f commit 286e9cf

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/BootstrapBlazor/Extensions/FieldIdentifierExtensions.cs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
// Maintainer: Argo Zhang([email protected]) Website: https://www.blazor.zone
55

66
using Microsoft.AspNetCore.Components.Forms;
7+
using Microsoft.Extensions.Localization;
8+
using System.Reflection;
79

810
namespace BootstrapBlazor.Components;
911

@@ -32,4 +34,30 @@ public static class FieldIdentifierExtensions
3234
/// <param name="fieldIdentifier"></param>
3335
/// <returns></returns>
3436
public static RangeAttribute? GetRange(this FieldIdentifier fieldIdentifier) => Utility.GetRange(fieldIdentifier.Model, fieldIdentifier.FieldName);
37+
38+
/// <summary>
39+
/// 获得 <see cref="RequiredValidator"/> 实例
40+
/// </summary>
41+
/// <param name="fieldIdentifier"></param>
42+
/// <param name="localizerFactory"></param>
43+
/// <returns></returns>
44+
public static RequiredValidator? GetRequiredValidator(this FieldIdentifier fieldIdentifier, IStringLocalizerFactory localizerFactory)
45+
{
46+
RequiredValidator? validator = null;
47+
var pi = fieldIdentifier.Model.GetType().GetPropertyByName(fieldIdentifier.FieldName);
48+
if (pi != null)
49+
{
50+
var required = pi.GetCustomAttribute<RequiredAttribute>(true);
51+
if (required != null)
52+
{
53+
validator = new RequiredValidator()
54+
{
55+
LocalizerFactory = localizerFactory,
56+
ErrorMessage = required.ErrorMessage,
57+
AllowEmptyString = required.AllowEmptyStrings
58+
};
59+
}
60+
}
61+
return validator;
62+
}
3563
}

0 commit comments

Comments
 (0)