Pre Validating Property in class

Mar 12, 2013 at 8:26 PM
All my classes are pre validating properties before making changes to ensure all object properties are always in valid state. Validator instance is injected via constructor. My property looks something like this
private string _Name;
public string Name {
    get { return _Name; }
    set {
        if (!Equals(_Name, value) && IsValid(x => x.Name)) {
            _Name = value;
            OnPropertyChanged(x => x.Name);
        }
    }
}
Now, since fluent validation is always validating property value, not new value-to-be, I've changed it to something like this
private string _Name;
public string Name {
    get { return _Name; }
    set {
        if (!Equals(_Name, value)) {
            string _oldValue = _Name;
            _Name = value;
            if (IsValid(x => x.Name)) {
                OnPropertyChanged(x => x.Name);
            } else {
                _Name = oldValue;
            }
        }
    }
}
but every inch of my body is telling me that this is not the way to do it.
Am i missing something? Is there any way I can specify value to be validated (validate "value" instead of "_Name")?
Coordinator
Mar 13, 2013 at 10:10 AM
No, this isn't something that's doable with FluentValidation.

FluentValidation is designed to validate pre-populated object instances, typically view-models that directly represent the input that the user has entered in your UI. You'd then validate the object as a whole, which gives the advantage of being able to do cross-property validation for example.

The approach you're trying to achieve looks like the type of validation that you'd more typically apply to a domain entity, which shouldn't even be allowed to exist in an invalid state (hence the guard checks within the property setters). These are two different approaches to validation which you'd typically apply to different type of objects...FluentValidation isn't designed to work with the latter, so if this is the approach you want then you'd probably be better off using a different library for validation.

Jeremy
Mar 13, 2013 at 10:23 AM
Thank you for a detailed explanation Jeremy.

You're right, this is a domain entity validation in classes that also implement IDataErrorInfo and IValidatableObject interfaces to support Entity Framework and WinForms validation out of the box. I was able to hook up both interface implementations to work nicely with Fluent Validate, "only" problem was validating before property is actually changed.

I'm currently doing all the validation manually inside classes without any framework and without possibility to inject different validators.
If someone has some suggestion of some other validation frameworks please let me know.

Thank you for a excellent library Jeremy.
Keep up the good work.