I'm building a custom web part with a custom toolpart to edit its custom properties.

I'm wondering where should I valide the values.

I can see two places where I can validate.

Either in the property itself:

    private int? m_MaxNumberOfSomething;

    public int? MaxNumberOfSomething
            return m_MaxNumberOfSomething;
            if (value.HasValue && value < 1) throw new WebPartPageUserException("At least one !");
            m_MaxNumberOfSomething = value;

Or in the apply changes of the toolpart method :

    public override void ApplyChanges()
        int maxNumberOfSomething;
        if (!int.TryParse(txtMaxNumberOfSomething.Text, out maxNumberOfSomething))
            throw new WebPartPageUserException("At least one");
        ParentWebPart.MaxNumberOfSomething = maxNumberOfSomething;

Is there any 3rd way?

What is the correct place to add such validation?

1 Answer 1


I would do it in the setter.

As you are throwing an Exception anyways it is cleaner to not let the user set the value in the first place. If you would do validation only in the ApplyChanges method, other code might have worked with the already wrongly set value.

Validate in set, so the user isn't even allowed to write invalid stuff to your variable. Here is a blog post showing exactly that method, but you do it correctly anyways.

  • Thanks for the link. However, what about complex validation? For example, imagine i have two integer properties, A and B and a rule that states A+B must be less than 100?
    – Steve B
    Commented Feb 19, 2013 at 6:22
  • Well the validation in the WebPart Properties are very "stupid". Throwing an exception for a validation error? I don't think that's clean. As for your example where one value depends on the value of the other: I would do that in the ApplyChanges method as it involves multiple fields. If you're talking about a single field, do it in the setter.
    – Dennis G
    Commented Feb 19, 2013 at 7:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.