This is just a C# function that validate an internet URL to see whether it is a valid URL format. The function uses Regular Expression to validate input URL and an example in an ASP.net page will also be provided.
1. C# validate URL function
public bool validate_url(string internet_url) { Regex reg = new Regex(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"); return reg.IsMatch(internet_url); } |
2. Put them all together with example in ASP.net page
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text.RegularExpressions; public partial class csharp_validate_url : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string url = "http://4rapiddev.com"; if (validate_url(url)) { Response.Write(url + " is a VALID internet URL"); } else { Response.Write(url + " is NOT a valid internet URL"); } //Output: http://4rapiddev.com is a VALID internet URL } public bool validate_url(string internet_url) { Regex reg = new Regex(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"); return reg.IsMatch(internet_url); } } |
Note: you need to declare System.Text.RegularExpressions namespace in order for Regex class works properly.