1 // Copyright 2004-2007 Castle Project - http://www.castleproject.org/
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 namespace Castle
.Components
.Validator
18 using System
.Reflection
;
21 /// Validates that the content has not been set to the specified value
23 public class ValidateNotSameValueAttribute
: AbstractValidationAttribute
25 private readonly object value;
28 /// Initializes a new instance of the <see cref="ValidateSameAsAttribute"/> class.
30 public ValidateNotSameValueAttribute(object mustNotBeThisValue
)
32 value = mustNotBeThisValue
;
36 /// Initializes a new instance of the <see cref="ValidateNotSameValueAttribute"/> class.
38 /// <param name="valueType">Type of the value.</param>
39 /// <param name="mustNotBeThisValue">The must not be this value.</param>
40 public ValidateNotSameValueAttribute(Type valueType
, object mustNotBeThisValue
)
41 : this(valueType
, mustNotBeThisValue
, null)
46 /// Initializes a new instance of the <see cref="ValidateSameAsAttribute"/> class.
48 public ValidateNotSameValueAttribute(Type valueType
, object mustNotBeThisValue
, string errorMessage
)
51 if (mustNotBeThisValue
== null)
53 throw new ArgumentException(
54 "You cannot use ValidateNotSameValue validator for null values, use ValidateNotEmpty for this");
56 if (typeof(IConvertible
).IsAssignableFrom(valueType
))
57 value = Convert
.ChangeType(mustNotBeThisValue
, valueType
);
60 MethodBase createInstance
= valueType
.GetMethod("Parse", BindingFlags
.Public
| BindingFlags
.Static
);
61 if (createInstance
!= null)
63 value = createInstance
.Invoke(null, new object[] {mustNotBeThisValue}
);
65 ConstructorInfo ctor
= valueType
.GetConstructor(new Type
[] {mustNotBeThisValue.GetType()}
);
68 throw new ArgumentException(
69 "valueType must be a type that implements IConvertible, or have a Parse method, or have a constructor that accept a " +
70 mustNotBeThisValue
.GetType()
73 value = Activator
.CreateInstance(valueType
, mustNotBeThisValue
);
78 /// Constructs and configures an <see cref="IValidator"/>
79 /// instance based on the properties set on the attribute instance.
81 /// <returns></returns>
82 public override IValidator
Build()
84 IValidator validator
= new NotSameValueValidator(value);
85 ConfigureValidatorMessage(validator
);