Reputation: 5701
Javascript function get an array as argument, this is input.
var ValidCoordinates = [
"-23, 25",
"4, -3",
"24.53525235, 23.45235",
"04, -23.234235",
"0, 1,2",
"0.342q0832, 1.2324v"
"43.91343345, 143"
];
After that we call function inside a loop certainly:
isValidCoordinates(ValidCoordinates[i])
I have created a function to solve this problem:
function isValidCoordinates(coordinates){
var args = coordinates.split(",");
var lat = /^(-?[1-8]?\d(?:\.\d{1,18})?|90(?:\.0{1,18})?)$/;
var lon = /^(-?(?:1[0-7]|[1-9])?\d(?:\.\d{1,18})?|180(?:\.0{1,18})?)$/;
//var re = ^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7])|([1-9]?\d)(\.\d+)?)$;
console.log(args[1]);
if(args[0].match(lat) == true && args[1].match(lon) == true){
return true;
} else{
return false;
}
}
lat
and lon
variables meet the requirements, I think, but regex match fails always. re
is another one regex, that could maybe match all two values.
Upvotes: 1
Views: 1504
Reputation: 627609
You have spaces in between your GPS values, thus, split with the following regex:
var args = coordinates.split(/,\s+/);
The \s+
matches one or more whitespaces.
See JS demo:
var ValidCoordinates = [
"-23, 25",
"4, -3",
"24.53525235, 23.45235",
"04, -23.234235",
"1, 1,2",
"43.91343345, 143"
];
isValidCoordinates(ValidCoordinates[4]);
function isValidCoordinates(coordinates){
var args = coordinates.split(/,\s+/);
var lat = /^(-?[1-8]?\d(?:\.\d{1,18})?|90(?:\.0{1,18})?)$/;
var lon = /^(-?(?:1[0-7]|[1-9])?\d(?:\.\d{1,18})?|180(?:\.0{1,18})?)$/;
console.log("'" + args[0] + "', '" + args[1] + "'");
if(lat.test(args[0].trim()) == true && lon.test(args[1].trim()) == true){
console.log("Yes");
} else{
console.log("No");
}
}
Upvotes: 2
Reputation: 13712
From the point of view understandability I think it would make more sense to parse the values and validate them using number comparison.
var coordsStrings = [
"-23, 25",
"4, -3",
"24.53525235, 23.45235",
"04, -23.234235",
"43.91343345, 143",
"443.91343345, 143",
"r43.91343345, 143"
];
var coordsNumbers = coordsStrings.map(function(coordsString) {
return coordsString
.split(/\s*,\s*/)
.map(function(coordString) {
return Number.parseFloat(coordString);
});
});
// the value of coordsNumbers = [
// [-23, 25]
// [4, -3]
// [24.53525235, 23.45235],
// [4, -23.234235],
// [43.91343345, 143]
// ];
// and then your validate logic
//Latitude = -90 -- +90
//Longitude = -180 -- +180
var isValid = function(coordNumbers) {
var lat = coordNumbers[0];
var lng = coordNumbers[1];
return lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180;
};
for (var i = 0; i < coordsNumbers.length; i++) {
var v = isValid(coordsNumbers[i]);
/*...*/
document.write(coordsNumbers[i][0] + ', ' + coordsNumbers[i][1] + ' is ' + (v ? 'valid':'<strong>invalid</strong>')+'</br>');
}
Upvotes: 1