comparison Source/Validation/RegExAttribute.cs @ 0:f990fcb411a9

Копия текущей версии из github
author cin
date Thu, 27 Mar 2014 21:46:09 +0400
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:f990fcb411a9
1 using System;
2 using System.Text.RegularExpressions;
3
4 namespace BLToolkit.Validation
5 {
6 [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
7 public class RegExAttribute : ValidatorBaseAttribute
8 {
9 public RegExAttribute(string pattern)
10 : this(pattern, RegexOptions.IgnorePatternWhitespace
11 #if !SILVERLIGHT
12 | RegexOptions.Compiled
13 #endif
14 )
15 {
16 }
17
18 public RegExAttribute(string pattern, RegexOptions options)
19 {
20 _pattern = pattern;
21 _options = options;
22 }
23
24 public RegExAttribute(string pattern, string errorMessage)
25 : this(pattern)
26 {
27 ErrorMessage = errorMessage;
28 }
29
30 public RegExAttribute(string pattern, RegexOptions options, string errorMessage)
31 :this(pattern, options)
32 {
33 ErrorMessage = errorMessage;
34 }
35
36 [Obsolete("Use RegExAttribute.Pattern instead.")]
37 public string Value { get { return Pattern; } }
38
39 private readonly string _pattern;
40 public string Pattern { get { return _pattern; } }
41
42 private readonly RegexOptions _options;
43 public RegexOptions Options { get { return _options; } }
44
45 #if !SILVERLIGHT
46 [NonSerialized]
47 #endif
48 private Regex _validator;
49 public Regex Validator
50 {
51 get
52 {
53 if (_validator == null)
54 _validator = new Regex(_pattern, _options);
55
56 return _validator;
57 }
58 }
59
60 public override bool IsValid(ValidationContext context)
61 {
62 if (context.IsNull(context))
63 return true;
64
65 Match match = Validator.Match(context.Value.ToString());
66
67 return match.Success && match.Value == context.Value.ToString();
68 }
69
70 public override string ErrorMessage
71 {
72 get { return base.ErrorMessage ?? "'{0}' format is not valid."; }
73 set { base.ErrorMessage = value; }
74 }
75 }
76 }