Validation Block doesn't pass simple validation test

Topics: Validation Application Block
Oct 24, 2007 at 4:05 AM
Edited Oct 24, 2007 at 4:08 AM
I created my first Validation code.
I pretty much copied the example straight from the documentation, but not quite.
Here's all my code, and for some reason, the test below fails.

Am I doing something stupid or does the Validation Block not work?

public class CurrencyCode : DomainObject
	{
		[StringLengthValidator(1, 3, MessageTemplate="Currency Code must be between 1 and 3 characters")]
		private readonly string _code;
 
		public CurrencyCode(string code)
		{
			_code = code;
		}
 
		public string Code
		{
			get { return _code; }
		}
	}

[TestFixture]
	public class CurrencyCodeTest : DomainModelTest
	{
		[Test]
		public void CanValidate()
		{
			CurrencyCode validCode = new CurrencyCode("AUD");
			Assert.That(Validation.Validate(validCode).IsValid, Is.True);
 
			CurrencyCode invalidCode = new CurrencyCode("AUDX");
			Assert.That(Validation.Validate(invalidCode).IsValid, Is.False);
		}
	}
Oct 25, 2007 at 4:16 AM
Hi,

Validation applies only to public fields and properties.

Fernando
Oct 26, 2007 at 8:13 AM
Edited Oct 26, 2007 at 8:14 AM
Yep, that fixes it. The sample code that I copied from, cunningly and unexpectedly, had a 'public' class variable.

Although, isn't it strange that IsValid returns true after I've completely used it incorrectly?
The first Assert in the test above passes!

Shouldn't it always return false? After all, a bool always returns false by default (unless it's explicitly set to true).
Feb 3, 2008 at 12:38 AM
Shouldn't it always return false? After all, a bool always returns false by default (unless it's explicitly set to true).

I now appreciate why this doesn't happen. Having just written and tested an NHibernate Interceptor that uses the Validation Application Block.
If the validator returned false on classes which I had no validation setup on, for example, everything would fail.

It means I would be 'forced' to put some validation on everything to get passed it. So, of course, the default has to be true.
Properties without any validation set on them, have to be considered neutral and therefore pass as valid.