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

前端 未结 3 1562
野的像风
野的像风 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: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

提交回复
热议问题