Powered by Blogger.

Saturday, February 15, 2014

Validate URL using regular expression in Asp.Net

In this post we will discuss how we can validate an URL (both http and https) using regular expression validator in Asp.net. Also you can check out my previous posts on:

- Difference between web application and web site in Asp.Net

- File upload and thumbnail creation in Asp.Net

- JavaScript Functions example

Through regular expression we can validate an internet url address. The validation expression for this is:

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

This will validate both http and https. Below is the full code:

.aspx code:

        Enter URL:
        <asp:TextBox ID="txtURL" runat="server"></asp:TextBox><asp:RegularExpressionValidator
            ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtURL" ErrorMessage="Enter a valid URL"
            ForeColor="Red" ValidationExpression="http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"></asp:RegularExpressionValidator>
        <br />
        <asp:Button ID="btnSubmitURL" runat="server" Text="Submit URL" />

If you will not put a valid url then the error will come like below: