How can I use a regular expression to validate the latitude and longitude for these text fields and display an error message?
<script type="text/javascript">
var latitude = document.getElementById(lat).value;
var longitude = document.getElementById(lng).value;
var reg = new RegExp("^-?([1-8]?[1-9]|[1-9]0)\.{1}\d{1,6}");
if( reg.exec(latitude) ) {
//do nothing
} else {
//error
}
if( reg.exec(longitude) ) {
//do nothing
} else {
//error
}
</script>
I used two different regexes for each value.
Latiude Regex:
const latRegex = /^-?([1-8]?[1-9]|[1-9]0)\.{1}\d{1,15}/g;
Longitude Regex:
const lngRegex = /^-?(([-+]?)([\d]{1,3})((\.)(\d+))?)/g;
Feel free to test your regex here:
^-?([1-8]?[1-9]|[1-9]0)\.{1}\d{1,6}
Debuggex Demo
In this case, the regex would match a number that is negative or positive, either (1 digit excluding '0' and a '0') or (one or two digits, the first one excluding 9, both excluding '0'), followed by a decimal point and up to 6 other digits. If that's what you need, then yes, this would work. If you need a different format, post it in a comment and I'll try to work a proper regex.
Googling "regex" should give you all the info you need.
If you just need numbers between -90 and 90 (or -180 and 180) you can just do this:
if (typeof num === 'number' && num <= 90 && num >= -90)
//valid
else
//invalid
If you need symbols like ° (degrees) or compass direction, then regex could be beneficial.
Here is a review of a few formats:
http://www.geomidpoint.com/latlon.html