We can take your startup from idea to revenue.   Find out more ยป


Validation using Regular Expressions

General Development, Ruby

I stumbled across a great resource for using regular expressions to validate different types of data. Here is a subset of the list that I found most useful:

EMAIL:
^[\w\-\+\&\*]+(?:\.[\w\-\+\&\*]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$  

CREDIT CARD:
^((4\d{3})|(5[1-5]\d{2})|(6011))-?\d{4}-?\d{4}-?\d{4}|3[4,7]\d{13}$  

MAC ADDRESS :
^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$  

IP ADDRESS :
^\b((25[0-5]|2[0-4]\d|[01]\d\d|\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]\d\d|\d?\d)\b$  

REASONABLE DOMAIN NAME:
^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$

For Ruby, you can use String::match method to determine if any results were returned:

    pattern = /pattern_goes_here/
    match = pattern.match(mystring)
    # print the first result back from the match
    puts match[0]

James @ April 23, 2006

Leave a comment


Feed Contact Us