"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Friday, May 14, 2010

To check given String is Url or not using Regular Expression

Hi everyboday,
Few days back my friend ask me abt validating a  string that it contain a url or not.
Visual stdio is giving us a in-build option to check this so what v need is to cal this control on server side and validate it Simple :) 

To call Regular Expression on server side v need to add a name space
using System.Text.RegularExpressions;


validate URL's without http
 
Private bool ValidateUrl(string url)
{
// regex pattern for url validation string
Regex RgxUrl = new Regex("(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?");
if (RgxUrl.IsMatch(url))
{
return true;// string url contain valid url
}
else
{
return false;
// string url contain invalid url
}

}


validate URL's with http



 

Private bool ValidateUrl(string url)
{
System.Globalization.CompareInfo cmpUrl = System.Globalization.CultureInfo.InvariantCulture.CompareInfo;
if(cmpUrl.IsPrefix(txtUrl.Text, "http://") == false)
{
txtUrl.Text = "http://" + txtUrl.Text;
}
Regex RgxUrl = new Regex("(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?");
if (RgxUrl.IsMatch(url))
{
return true;
}
else
{
return false;
}
}

Have a nice day... 'N happy Coding :)
 Hackers: Heroes of the Computer RevolutionHackersThe Web Application Hacker's Handbook: Discovering and Exploiting Security Flaws

No comments: