Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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;

    [Browsable(false)]
    [Category(Constants.WebPartsExtendedPropertiesCategoryName)]
    [DefaultValue(5)]
    [WebPartStorage(Storage.Personal)]
    public int? MaxNumberOfSomething
    {
        get
        {
            return m_MaxNumberOfSomething;
        }
        set
        {
            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?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

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.

share|improve this answer
    
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 Feb 19 '13 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 Feb 19 '13 at 7:36
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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