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
^[-+]?([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?
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.
One reason to use a regex may be to perform as-you-type partial string validation so as to prevent entry of an invalid value in the fist place, instead of catching an invalid final result after the user hits some submit button or key.
I suppose you could just try to coerce the string to a number and compare after each keystroke, but how does it deal with conversion of "-" and "." - I don't remember - its been many years since I cared about Javascript. The FSM of a compiled regex will be more efficient than this conversion process but it would be insignificant in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With