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
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
}
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;
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 :)
No comments:
Post a Comment