Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top