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.
16 using System
.Reflection
;
18 namespace Castle
.Components
.Validator
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 this.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)
47 /// Initializes a new instance of the <see cref="ValidateSameAsAttribute"/> class.
49 public ValidateNotSameValueAttribute(Type valueType
, object mustNotBeThisValue
, string errorMessage
)
52 if (mustNotBeThisValue
==null)
54 throw new ArgumentException(
55 "You cannot use ValidateNotSameValue validator for null values, use ValidateNotEmpty for this");
57 if (typeof(IConvertible
).IsAssignableFrom(valueType
))
58 this.value = Convert
.ChangeType(mustNotBeThisValue
, valueType
);
61 MethodBase createInstance
= valueType
.GetMethod("Parse",BindingFlags
.Public
|BindingFlags
.Static
);
62 if(createInstance
!=null)
64 this.value = createInstance
.Invoke(null, new object[] { mustNotBeThisValue }
);
66 ConstructorInfo ctor
= valueType
.GetConstructor(new Type
[] { mustNotBeThisValue.GetType() }
);
69 throw new ArgumentException(
70 "valueType must be a type that implements IConvertible, or have a Parse method, or have a constructor that accept a " + mustNotBeThisValue
.GetType()
73 this.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
);