Reputation: 2208
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
Upvotes: 4
Views: 4135
Reputation: 6586
I'm validating this way:
var ck_lat = /^-?([1-8]?\d(?:\.\d{1,})?|90(?:\.0{1,6})?)$/;
var ck_lon = /^-?((?:1[0-7]|[1-9])?\d(?:\.\d{1,})?|180(?:\.0{1,})?)$/;
var lat = 89.320615;
var lon = 179.400520;
if(ck_lat.test(lat) && ck_lon.test(lon)) {
//Was a valid latitude and longitude pair :)
}
This is on development stage, but it works ok, here is the link for testing both regexp:
Check Latitude: http://rubular.com/r/vodC5TW3lG
Check Longitude: http://rubular.com/r/3LIIcjFEQT
EDIT: Thanks to Tim Kelly for the improvement, this one catches -90 / -180, i think now is complete :) Links and code edited.
Upvotes: 10
Reputation: 173
Latitude ranges from -90 to 90 Longitude ranges from -180 to 180
I have used a regex which evaluate values which falls between the range having 4-6 decimal points (since in google maps api mostly 6 decimal points precision is used)
Latitude: /^(-?(90\.0{4,6})|([0-8]\d{0,1})\.\d{4,6})$/
http://rubular.com/r/UpY74Y4fuG
Longitude: /^(-?((180)\.0{4,6})|((1[0-7][0-9])|([0-9]\d{0,1}))\.\d{4,6})$/
http://rubular.com/r/OQ0KS7puhv
Upvotes: 1
Reputation: 3859
/^-?\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*$/
Upvotes: 9
Reputation: 28402
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.
Upvotes: 6