0

How can I restrict an input field for enter latitude using javascript?

The following is the piece nof code which i have tried.

$('#latitude').on( "keypress",function (e) {
        var keypress = e.keyCode || e.which || e.charCode; 
        var key = String.fromCharCode(keypress);
        var regEx = /^[-|+]?[0-9]{0,2}(.[0-9]{0,6})?$/;

        var txt = $(this).val() + key;
        if (!regEx.test(txt)) {
            if(keypress != 8){
                e.preventDefault();
            }else{
            }
        }else{

        }
    });

Here i found the issue that i can enter a special character at the first position. Please help me...

kcak11
  • 832
  • 7
  • 19
johncy binoy
  • 53
  • 2
  • 3
  • 9

3 Answers3

0

In your validation also include the following line:

if (!regEx.test(txt) && !isNaN(txt)) { .... }
kcak11
  • 832
  • 7
  • 19
0

try this, also note that N and S can also be included in latitude

"^(?:90|[0-8][0-9]):[0-5][0-9]:[0-5][0-9][NS]$"
124
  • 2,757
  • 26
  • 37
0

This question has already been answered here Regular expression for matching latitude/longitude coordinates?.
It suggests the following regular expression:
^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$

Community
  • 1
  • 1