Whenever I had to add a string to a web controls control collection I’ve always used the Literal control like this:

Literal str = new Literal();

str.Text = "hello world";

Page.Controls.Add(str);

I have always thought a Literal was too cumbersome to use for a simple thing like adding a string to a controls control collection. Then, the other day, I found the LiteralControl while browsing through the MSDN docs and that my friends are a real treat. It lives in the System.Web.UI namespace and it adds great value. You can use it to achieve the same task as the one above, but in a more natural way.

>

Page.Controls.Add(new LiteralControl("Hello world"));

It’s much cleaner, much nicer and much simpler. Now I can’t live without it.

Today, I had to build web form that took user input from standard ASP.NET input controls. In one of the text boxes the user must to enter a valid URL, so I had to make some validation logic. But first of all, I had to find out what kind of URL’s we would accept as being valid. These are the rules we decided upon:

  • The protocol must be http or https
  • Sub domains are allowed
  • Query strings are allowed

Based on those rules, I wrote this regular expression:

(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

It is used in a RegularExpressionValidator control on the web form and on a business object in C#.

<asp:RegularExpressionValidator runat="Server"

  ControlToValidate="txtUrl"

  ValidationExpression="(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"

  ErrorMessage="Please enter a valid URL"

  Display="Dynamic" />

Here is the server-side validator method used by the business object:

using System.Text.RegularExpressions;

 

private bool IsUrlValid(string url)

{

  return Regex.IsMatch(url, @"(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");

}

You can add more protocols to the expression easily. Just add them to the beginning of the regular expression:

(http|https|ftp|gopher)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

You can also allow every thinkable protocol containing at least 3 characters by doing this:

([a-zA-Z]{3,})://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?