Using regular expression to validate latitude and longitude coordinates then display error

前端 未结 3 1544
野的像风
野的像风 2020-12-17 00:39

How can I use a regular expression to validate the latitude and longitude for these text fields and display an error message?

 
相关标签:
3条回答
  • 2020-12-17 01:06
    <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>
    
    0 讨论(0)
  • 2020-12-17 01:11

    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;

    0 讨论(0)
  • 2020-12-17 01:18

    Feel free to test your regex here:

    ^-?([1-8]?[1-9]|[1-9]0)\.{1}\d{1,6}
    

    Regular expression visualization

    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

    0 讨论(0)
提交回复
热议问题