0

I have defined 2 regular expressions.

ip_regex = /^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/
hostname_regex = /^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$/

I need to allow users to input either an IP address or a Hostname in to a textfield. My validation code is as follows.

validates :ip_address,  :presence => true,
                        :format   => { :with => ip_regex || hostname_regex }

I've verified that the ip_regex is successful. However, the hostname_regex isn't. It appears that either the hostname_regex or my validation code is flawed. Which is it? How do I resolve this issue? Is there a more effective &/or efficient way of performing this task?

Mentat
  • 70
  • 1
  • 8

2 Answers2

0
^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$

-> http://www.mkyong.com/regular-expressions/10-java-regular-expression-examples-you-should-know/

Tobias
  • 9,170
  • 3
  • 24
  • 30
0

I think nothing wrong with your hostname_regex.

You can use regular expression OR(|) operator to match more than one format.Just seperate regular expressions by | operator.

validates :ip_address,  :presence => true,
:format   => { :with =>/(^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$)|(^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$)/ }  

Refer

Soundar Rathinasamy
  • 6,658
  • 6
  • 29
  • 47