0
|
1 using System;
|
|
2
|
|
3 namespace BLToolkit.Validation
|
|
4 {
|
|
5 [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
|
|
6 public class MaxLengthAttribute : ValidatorBaseAttribute
|
|
7 {
|
|
8 public MaxLengthAttribute(int maxLength)
|
|
9 {
|
|
10 _value = maxLength;
|
|
11 }
|
|
12
|
|
13 public MaxLengthAttribute(int maxLength, string errorMessage)
|
|
14 : this(maxLength)
|
|
15 {
|
|
16 ErrorMessage = errorMessage;
|
|
17 }
|
|
18
|
|
19 private readonly int _value;
|
|
20 public int Value
|
|
21 {
|
|
22 get { return _value; }
|
|
23 }
|
|
24
|
|
25 public override bool IsValid(ValidationContext context)
|
|
26 {
|
|
27 return context.IsNull(context) || context.Value.ToString().Length <= _value;
|
|
28 }
|
|
29
|
|
30 public override string ErrorMessage
|
|
31 {
|
|
32 get { return base.ErrorMessage ?? "'{0}' maximum length is {1}."; }
|
|
33 set { base.ErrorMessage = value; }
|
|
34 }
|
|
35
|
|
36 public override string GetErrorMessage(ValidationContext context)
|
|
37 {
|
|
38 return string.Format(ErrorMessage, GetPropertyFriendlyName(context), Value);
|
|
39 }
|
|
40 }
|
|
41 }
|