As a follow up to my last post I decided to figure out how to use FluentValidation to validate user settings.

My.Settings  is a  convenient way of storing settings, but out of the box that is about all it does. Before figuring this out I used to manually wrap the My.Settings class in my own class and use the My.Settings properties as backing store for my wrapper properties. This is a boring and tedious job when you more than a couple properties. It seemed like there should be a better way…

I’ve often attempted to find articles on an easier/better way to validate My.Settings but I’ve not had much luck.  I was really surprised to find that nobody has done something like this before.  Either most people don’t need to validate the settings, they don’t use My.Settings, or there is some problem with the way I’m doing it which I haven’t discovered yet. If anyone knows of a better way then by all means share!

One example of the need for validation is user settings for common variables. If I let the user set a common variable I need to make sure that it is in range and that it does not conflict with another common variable setting.  To accomplish this using the FluentValidation library I created two rules. I broke it up into two separate rules so that I could keep the default message for the range and have a different message for the overlap.

RuleFor(Function(s) (s.SetVariable)).
 NotNull.InclusiveBetween(1, 200)

RuleFor(Function(s) (s.SetVariable)).
 NotEqual(Function(s) (s.ResetVariable)).
 WithMessage("This variable number is already being used")

I setup the MySettings class that like I did the Part class in my last post.  It implements the IDataErrorInfo interface allowing me to notify the user of a problem.  I then bound the settings to text boxes.

Download Example Project: WpfSettingsBindingWithValidation

About jweaver

Service Tech at Gosiger Michigan. Twitter: @jon_weaver6

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s