Validating Url, Email, IP

by volkanuzun 11/8/2008 9:41:00 AM

In one of the project i am working at, i need to validate a url, an email and ip address. I googled so many regular expressions, and almost %99 of the ones i found had some issues :). I collected the working one, in an extension class, so that i can use extensions to validate now. Here is the class i have:

public static  class Validations {

 

        public static bool IsValidEmail(this string Email)

        {

            if (String.IsNullOrEmpty(Email))

                return false;

            string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}"+

                                @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +

                                @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

            Regex re = new Regex(strRegex);

            if (re.IsMatch(Email))

                return (true);

           

           return (false);

        }

 

        public static bool IsValidIPAddress(this string IP)

        {

            if(String.IsNullOrEmpty(IP))

                return false;

            IPAddress ipAddress;

            bool valid = IPAddress.TryParse(IP, out ipAddress);

            return valid;

        }

 

        public static bool IsValidUrl(this string Url)

        {

            if(String.IsNullOrEmpty(Url))

                return false;

            string strRegEx = @"^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)"+

                            @"?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*"+

                            @"(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$";

           Regex re = new Regex(strRegEx);

            if(re.IsMatch(Url))

                return true;

            return false;

        }

    }

 

Have fun :) 

Tags:

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading



About the author

Volkan Uzun




E-mail me Send mail

Twitter

Calendar

<<  January 2009  >>
MoTuWeThFrSaSu
2930311234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar

Flickr Badge

www.flickr.com
This is a Flickr badge showing public photos from volkanuzun. Make your own badge here.

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2009

Sign in