views:

46

answers:

2

Hi guys,

I'm trying to do a validates_format_of on the latlng object that is passed back from Google Maps API. I've got the map set up perfectly so that when I click on a point in the map it fills in a text-field with the latlng (which looks like this: 46.320615137905904, 9.400520324707031). I'm storing this value as a string in the db (which I then parse out to place markers on the map later) but I need to validate the format of the sting as two floats (positive or negative) with a comma in between.

I know that this is possible with regex but for the life of my haven't been able to figure out the regex string to get it working.

Any help would be super appreciated! Thanks! Jeff

+3  A: 

It is possible with a Regex, however you may find it easier to use split as follows

latitude, longitude = latlong.split(',')

And then check the numericality of the two variables.

Steve Weet
I prefer this solution, because it also lends itself to range-checking the values (should be between -180 to 180).
Chris
@Chris -180 to +180 is good for longitude, latitude is -90 to +90
Steve Weet
+2  A: 

/^-?\d+\.\d+\,\s?-?\d+\.\d+$/

  • ^ matches the beginning of the
  • $ matches the end of the string
  • -? matches an optional minus sign
  • \d+ matches 1 or more digits
  • \. mathces a dot (you have to escape it because . matches any character)
  • \s? matches an optional whitespace

You may want to accept whitespaces at the beginning or at the end:

/^\s*-?\d+\.\d+\,\s?-?\d+\.\d+\s*$/

Leventix
Tested and works http://rubular.com/r/efAZkpiNMl.One suggestion @Leventix: `/^\s*[-+]?\d+\.\d+\,\s?[-+]?\d+\.\d+\s*$/` allowing both + and -. Cool solution btw. :)
Shripad K
Another suggestion: `/^\s*[-+]?\d{1,3}\.\d+\,\s?[-+]?\d{1,3}\.\d+\s*$/` - since Lat and Long should be between 0 and 180.
Chris
Cheers guys! And thanks for the explanation - that will help me having to ask later on!
erskingardner