David Moles - 4 months ago 20

Javascript Question

When I search for

`validate latitude longitude [javascript]`

In fairness, some of these OPs did

`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

`^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$`

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

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.