yavsc/src/Yavsc.Abstract/Attributes/Validation/YaStringLength.cs

58 lines
1.7 KiB
C#
Raw Normal View History

2019-06-16 01:10:52 +01:00
using System;
2017-10-04 23:53:47 +02:00
namespace Yavsc.Attributes.Validation
{
2019-06-21 09:20:13 +01:00
public partial class YaStringLength: YaValidationAttribute
2017-10-04 23:53:47 +02:00
{
2019-06-17 01:04:46 +01:00
public long MinimumLength { get; set; } = 0;
2017-10-04 23:53:47 +02:00
private long maxLen;
2019-06-16 21:09:50 +01:00
public YaStringLength(long maxLen) : base( ()=> "BadStringLength")
2017-10-04 23:53:47 +02:00
{
this.maxLen = maxLen;
2019-06-21 09:20:13 +01:00
UseDefaultErrorMessage();
}
public YaStringLength(long minLen, long maxLen) : base( ()=> "BadStringLength")
{
this.maxLen = maxLen;
this.MinimumLength=minLen;
UseDefaultErrorMessage();
}
void UseDefaultErrorMessage()
{
if (ErrorMessageResourceType==null) {
2019-09-04 01:25:36 +01:00
ErrorMessageResourceType = typeof(Yavsc.Attributes.Validation.Resources);
2019-06-21 09:20:13 +01:00
ErrorMessageResourceName = "InvalidStringLength";
}
2017-10-04 23:53:47 +02:00
}
public override bool IsValid(object value) {
2019-06-16 01:10:52 +01:00
2017-10-04 23:53:47 +02:00
if (value == null) {
return false;
}
2019-06-16 01:10:52 +01:00
2017-10-04 23:53:47 +02:00
string stringValue = value as string;
if (stringValue==null) return false;
2019-06-16 21:09:50 +01:00
if (MinimumLength>=0)
2017-10-04 23:53:47 +02:00
{
2019-06-17 01:04:46 +01:00
if (stringValue.Length< MinimumLength) {
return false;
}
2017-10-04 23:53:47 +02:00
}
if (maxLen>=0)
{
if (stringValue.Length>maxLen) {
return false;
}
}
return true;
}
2019-06-16 21:09:50 +01:00
public override string FormatErrorMessage(string name)
{
var temp = base.FormatErrorMessage(name);
return string.Format(temp, MinimumLength, maxLen);
}
2019-06-16 01:10:52 +01:00
2017-10-04 23:53:47 +02:00
}
}