Javascript regex to validate GPS coordinates

Viewed 13514

I have a form where a user inserts the GPS coordinates of a location to a corresponding photo. Its easy enough to filter out invalid numbers, since I just have to test for a range of (-90, 90), (-180, 180) for lat/long coordinates.

However, this also means that regular text is valid input.

I've tried changing the test pattern to

var pattern= "^[a-zA-Z]" 

and is used in the function to detect alphabetical characters

$(".lat").keyup(function(){
  var thisID= this.id;
  var num = thisID.substring(3, thisID.length);
  var thisVal = $(this).val();

  //if invalid input, show error message and hide save button
  if (pattern.test(thisVal)){
    $("#latError"+num).fadeIn(250);
    $("#save"+num).fadeOut(100)
  } 
  else { //otherwise, hide error message and show save
    $("#save"+num).fadeIn(250);
    $("#latError"+num).fadeOut(100);
  }
});

However, this doesn't work as Firebug complains that pattern.test is not a function What would solve this issue?

5 Answers

@paul flemming gave a great answer, this answer extends his and includes longitude and uses typescript. I would suggest this in place of regex for speed and simplicity.

Since, parseFloat takes a string and returns a number isNaN check isn't needed. This function allows a string or a number and converts it to string for parseFloat and will then do the simple threshold tests against +-90 & +-180.

function isValidLatAndLong(lat: number |string, lon:number|string){
    const num1 = "" +lat; //convert toString
    const num2 = "" +lon;
    if (parseFloat(num1) <= 90 && parseFloat(num1) >= -90 && parseFloat(num2) <= 180 && parseFloat(num2) >= -180){
        return true;
    }
    else{
        return false;
    }
  }
Related