Pages

Search This Blog

Tuesday, June 14, 2011

Validate Browsable Property of a Web Part and show exception message in the Webpart’s Tool Pane

Many a times we are into a situation where we have to apply some validations on the custom browsable property of a webpart and if the value in the property is not valid than we need to show Exception message in the ToolPane of the webpart itself.
We can validate these properties and can show the exception message also. To do this we need to put the validation part in the “SET” part of Property definition itself as show below.
Suppose we have to create a property which will accept the XML strings only and we want to restrict the user to enter invalid XML string and show error message on the ToolPane of the webpart.
This requirement we can achieve by using Regular Expression. Below is the code snippet by which we can do this.
private string _QueryFilter;
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [Category("Display")]
        [WebDisplayName("CheckProperty")]
        [Description("Description of the Webpart")]
        public string QueryFilter
        {
            get { return _QueryFilter; }
            set
            {
                string pattern = @"<where><[^>]+>[^<]*</[^>]+></where>";
                System.Text.RegularExpressions.Match match =
                Regex.Match(value.Trim(), pattern, RegexOptions.IgnoreCase);
               
if (!match.Success)                  
                        throw new WebPartPageUserException("The query filter is not a valid Caml query string");
               

                _QueryFilter = value;
            }
        }

Now when we deploy this webpart property it will look like this


And after writing the XML string it will validate the string based upon our regular expression. If the expression is not valid than it will throw the WebPartPageUserException as shown below:


In this way we can validate the browsable property of the webpart.
Hope it will be a help to you!
Ravish

No comments:

Post a Comment