mirror of https://github.com/abpframework/abp.git
5 changed files with 104 additions and 5 deletions
@ -0,0 +1,45 @@ |
|||
using System.Globalization; |
|||
using Microsoft.AspNetCore.Mvc.DataAnnotations; |
|||
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; |
|||
using Microsoft.Extensions.Localization; |
|||
using Volo.Abp.Validation; |
|||
|
|||
namespace Volo.Abp.AspNetCore.Mvc.DataAnnotations |
|||
{ |
|||
public class DynamicMaxLengthAttributeAdapter : AttributeAdapterBase<DynamicMaxLengthAttribute> |
|||
{ |
|||
private readonly string _max; |
|||
|
|||
public DynamicMaxLengthAttributeAdapter( |
|||
DynamicMaxLengthAttribute attribute, |
|||
IStringLocalizer stringLocalizer) |
|||
: base(attribute, stringLocalizer) |
|||
{ |
|||
_max = Attribute.Length.ToString(CultureInfo.InvariantCulture); |
|||
} |
|||
|
|||
public override string GetErrorMessage(ModelValidationContextBase validationContext) |
|||
{ |
|||
Check.NotNull(validationContext, nameof(validationContext)); |
|||
|
|||
return GetErrorMessage( |
|||
validationContext.ModelMetadata, |
|||
validationContext.ModelMetadata.GetDisplayName(), |
|||
Attribute.Length |
|||
); |
|||
} |
|||
|
|||
public override void AddValidation(ClientModelValidationContext context) |
|||
{ |
|||
Check.NotNull(context, nameof(context)); |
|||
|
|||
MergeAttribute(context.Attributes, "data-val", "true"); |
|||
MergeAttribute(context.Attributes, "data-val-length", GetErrorMessage(context)); |
|||
|
|||
if (Attribute.Length != int.MaxValue) |
|||
{ |
|||
MergeAttribute(context.Attributes, "data-val-length-max", _max); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,39 @@ |
|||
using System; |
|||
using System.ComponentModel.DataAnnotations; |
|||
using System.Diagnostics; |
|||
using System.Reflection; |
|||
using JetBrains.Annotations; |
|||
|
|||
namespace Volo.Abp.Validation |
|||
{ |
|||
public class DynamicMaxLengthAttribute : MaxLengthAttribute |
|||
{ |
|||
private static readonly FieldInfo MaximumLengthField; |
|||
|
|||
static DynamicMaxLengthAttribute() |
|||
{ |
|||
MaximumLengthField = typeof(MaxLengthAttribute).GetField( |
|||
"<MaximumLength>k__BackingField", |
|||
BindingFlags.Instance | BindingFlags.NonPublic |
|||
); |
|||
Debug.Assert(MaximumLengthField != null, nameof(MaximumLengthField) + " != null"); |
|||
} |
|||
|
|||
public DynamicMaxLengthAttribute( |
|||
[NotNull] Type sourceType, |
|||
[CanBeNull] string maximumLengthPropertyName) |
|||
{ |
|||
Check.NotNull(sourceType, nameof(sourceType)); |
|||
|
|||
if (maximumLengthPropertyName != null) |
|||
{ |
|||
var maximumLengthProperty = sourceType.GetProperty( |
|||
maximumLengthPropertyName, |
|||
BindingFlags.Static | BindingFlags.Public |
|||
); |
|||
Debug.Assert(maximumLengthProperty != null, nameof(maximumLengthProperty) + " != null"); |
|||
MaximumLengthField.SetValue(this, (int) maximumLengthProperty.GetValue(null)); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue