最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript Google Map Coordinate Validation - Stack Overflow

programmeradmin3浏览0评论

I have a form where you can select a point on the map, and it populates lat and lon textboxes, or you can enter the coordinates yourself.

I need to add validation to make sure the user enters valid ranges, but I am not sure if I have the right RegEx. Here is the method I am using:

var regex_coords = "[-]?[0-9]*[.]{0,1}[0-9]";

// ...

valid_coords: function (number) {
if (number.match(regex_coords) && !isNaN(Number(number))) {
    $("#btnSaveResort").removeAttr("disabled");
    return true;
} else {
    $("#btnSaveResort").attr("disabled", "disabled");
    return false;
}
},

This function returns false no matter what I have entered in the textboxes.

Any suggestions on a better way?

I have a form where you can select a point on the map, and it populates lat and lon textboxes, or you can enter the coordinates yourself.

I need to add validation to make sure the user enters valid ranges, but I am not sure if I have the right RegEx. Here is the method I am using:

var regex_coords = "[-]?[0-9]*[.]{0,1}[0-9]";

// ...

valid_coords: function (number) {
if (number.match(regex_coords) && !isNaN(Number(number))) {
    $("#btnSaveResort").removeAttr("disabled");
    return true;
} else {
    $("#btnSaveResort").attr("disabled", "disabled");
    return false;
}
},

This function returns false no matter what I have entered in the textboxes.

Any suggestions on a better way?

Share Improve this question asked Jun 6, 2012 at 16:01 guyfromflguyfromfl 1,2123 gold badges13 silver badges24 bronze badges 1
  • stackoverflow./questions/5457522/… – ScottE Commented Jun 6, 2012 at 16:04
Add a ment  | 

2 Answers 2

Reset to default 14

Latitude and longitude have different ranges: latitude is (-90,90) and longitude is (-180,180), so using a single regex is not really going to work. You might also want to check that the latitude can be plotted on the map — which means that it needs to lie in the range (-85,85) approximately. Or you might want to limit the range to a bounding rectangle containing a particular area.

Why not explicitly test the ranges?

function inrange(min,number,max){
    if ( !isNaN(number) && (number >= min) && (number <= max) ){
        return true;
    } else {
        return false;
    };
}

You can then tailor your code for what you want. Presumably you only want to enable the save button if both latitude and longitude are valid.

valid_coords: function(number_lat,number_lng) {
    if (inrange(-90,number_lat,90) && inrange(-180,number_lng,180)) {
        $("#btnSaveResort").removeAttr("disabled");
        return true;
    }
    else {
        $("#btnSaveResort").attr("disabled","disabled");
        return false;
    }
}

Your regex looks incorrect. Try:

var regex_coords = /\-?[0-9]+[\.]{0,1}[0-9]*/;
发布评论

评论列表(0)

  1. 暂无评论