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

Pages

Saturday, June 25, 2011

Validating URL using C# with Regular Expression with and without http

Without using Http


    public 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;
        }
    }


By Using Http


    private bool ValidateHttpUrl(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 :)

No comments: