String Required & String.IsNotNull

May 22, 2010 at 9:44 PM

I suppose that string.Required means !string.IsNullOrEmpty. In my case it's not a Nullable<string>, but I will only prevent from beeing Null. If the string is equal to string.Empty or "", all is ok. What do you suggest in my case? How would the expression look like?

May 23, 2010 at 3:05 AM

This was a little tricky because Required() on a string type will always evaluate to false for null or String.Empty. And if Required if false, then all the additional rules are not evaluated.

To solve this, you can take advantage of Check accepting any Expression. Instead of creating a Check() on the string property, you can add it to the T in Validates<T>instead and add an Expect to add your custom rule. For example:

public class Contact
    public string Name {get;set;}

public ContactSpec : Validates<Contact>
    public ContactSpec()
        //String.Empty for string types ok, but not Null's
Check(c => c).Required().Expect(contact, c) => c.Name != null, "Name is required.");



May 23, 2010 at 11:20 PM

Thanks a lot, I think this would work. Why you don't extend your framework to support following syntax:

Check(c => c.Name).IsNotNull();
Check(c => c.Name).IsNull();

So the "Property" of the ValidationResult would contain the correct Property information. Using the syntax above i have only the "Target".