David Moles David Moles - 1 year ago 117
Javascript Question

Why use regular expressions to validate latitude and longitude in Javascript?

When I search for

validate latitude longitude [javascript]
, I get answers that match digits indiscriminately or match the wrong range or are just too complicated to debug.

In fairness, some of these OPs did ask for regexes, and Javascript isn't my first language, but it seems like it would be more straightforward and less error-prone just to do the math:

function isLatitude(maybeLat) {
var latF = parseFloat(maybeLat)
if (isNaN(latF)) return false
return (latF >= -90 && latF <= 90)

function isLongitude(maybeLon) {
var lonF = parseFloat(maybeLon)
if (isNaN(lonF)) return false
return lonF >= -180 && lonF <= 180

Yes, it's less terse, but it's a lot more readable than


Is there some advantage to using regular expressions? Performance? Browser compatibility? Library tools that only allow regex validation? SO users showing off their mad regex sk1llz?

Answer Source

I absolutely think this is overkill / unnecessary use of a regex. I think your approach is correct, though it can be shortened somewhat:

function isLatitude(lat) {
  return isFinite(lat) && Math.abs(lat) <= 90;

function isLongitude(lng) {
  return isFinite(lng) && Math.abs(lng) <= 180;

isFinite will reject anything that isn't a (finite) number, or can't be automatically converted to a number (like a string containing a number). Also, I've taken to using lng to represent longitude since it's the same length as lat, and can't be confused with a keyword.

The Math library functions (and isFinite) will automatically coerce strings to numbers, if possible.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download