2 // NullableStringValidator.cs
5 // Atsushi Enomoto (atsushi@ximian.com)
6 // Lluis Sanchez Gual (lluis@novell.com)
8 // Permission is hereby granted, free of charge, to any person obtaining
9 // a copy of this software and associated documentation files (the
10 // "Software"), to deal in the Software without restriction, including
11 // without limitation the rights to use, copy, modify, merge, publish,
12 // distribute, sublicense, and/or sell copies of the Software, and to
13 // permit persons to whom the Software is furnished to do so, subject to
14 // the following conditions:
16 // The above copyright notice and this permission notice shall be
17 // included in all copies or substantial portions of the Software.
19 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
23 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
24 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
25 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
30 // copied StringValidator.cs and changed class name and just one line
31 // in Validate() (see there).
34 namespace System.Configuration
36 internal class NullableStringValidator: ConfigurationValidatorBase
38 char[] invalidCharacters;
42 public NullableStringValidator (int minLength)
44 this.minLength = minLength;
45 maxLength = int.MaxValue;
48 public NullableStringValidator (int minLength, int maxLength)
50 this.minLength = minLength;
51 this.maxLength = maxLength;
54 public NullableStringValidator (int minLength, int maxLength, string invalidCharacters)
56 this.minLength = minLength;
57 this.maxLength = maxLength;
58 if (invalidCharacters != null)
59 this.invalidCharacters = invalidCharacters.ToCharArray ();
62 public override bool CanValidate (Type type)
64 return type == typeof(string);
67 public override void Validate (object value)
69 // This is the only difference from StringValidator:
70 // null value is always allowed.
74 string s = (string) value;
75 if (s == null || s.Length < minLength)
76 throw new ArgumentException ("The string must be at least " + minLength + " characters long.");
77 if (s.Length > maxLength)
78 throw new ArgumentException ("The string must be no more than " + maxLength + " characters long.");
79 if (invalidCharacters != null) {
80 int i = s.IndexOfAny (invalidCharacters);
82 throw new ArgumentException (String.Format ("The string cannot contain any of the following characters: '{0}'.", invalidCharacters));