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?