Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex to validate GPS coordinates

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?

like image 593
Jason Avatar asked Jul 13 '12 17:07

Jason


2 Answers

This is what i use in my project:

app.user.ck_lat = /^(-?[1-8]?\d(?:\.\d{1,18})?|90(?:\.0{1,18})?)$/;
app.user.ck_lon = /^(-?(?:1[0-7]|[1-9])?\d(?:\.\d{1,18})?|180(?:\.0{1,18})?)$/;

function check_lat_lon(lat, lon){
  var validLat = app.user.ck_lat.test(lat);
  var validLon = app.user.ck_lon.test(lon);
  if(validLat && validLon) {
      return true;
  } else {
      return false;
  }
}

check_lat_lon(-34.11242, -58.11547) Will return TRUE if valid, else FALSE

I hope this will be usefull to you!

like image 95
mzalazar Avatar answered Sep 23 '22 18:09

mzalazar


Do you need to use regex? Consider the following:

var val = parseFloat(lat);
if (!isNaN(val) && val <= 90 && val >= -90)
    return true;
else
    return false;
like image 41
Paul Fleming Avatar answered Sep 24 '22 18:09

Paul Fleming