Abstract The most of the developer asking question inthe messageboard , how to valid URL using regex with C#. The bigest advantage in regex we can define a pattern in predfine way.then you could use the in the code. Implementaion {codecitation class="brush: c#; gutter: true;" width="600px"} 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; } else { return false; } }
{/codecitation} The above code will validate URL's without http also. Alternatively you can use this way to validate url {codecitation class="brush: c#; gutter: true;" width="600px"} 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; } } {/codecitation}
Incorporate in your project Use this Funtion in your project click on the rihgt hand side top copy code icon the paste in your one the class file. Then pass the your url string value to this function, if valid string it will return true, otherwise false. Thank you Amal. |