The following article will demonstrate how to validate latitude and longitude value using JavaScript and C#. Latitude and longitude are basic geographic terms that determine the location coordinate of any place located on earth.

To implement validation for latitude and longitude values we can write a logic that, latitude must be a number between -90 and 90 and the longitude between -180 and 180 degrees inclusive.

Validate latitude and longitude using JavaScript:

<script type="text/javascript"> function ValidateLatLng() { var lat = document.getElementById("txtLat").value; var lng = document.getElementById("txtLon").value; if (lat < -90 || lat > 90) { alert("Latitude must be between -90 and 90 degrees inclusive."); } else if (lng < -180 || lng > 180) { alert("Longitude must be between -180 and 180 degrees inclusive."); } else if (lat == "" || lng == "") { alert("Enter a valid Latitude or Longitude!"); } } </script>

and using C#:

using System; public class Validation { double _lat, _lng; public Double Lat { get { return this._lat; } set { if (value < -90 || value > 90) { throw new ArgumentOutOfRangeException("Latitude must be between -90 and 90 degrees inclusive."); } this._lat = value; } } public Double Lng { get { return this._lng; } set { if (value < -180 || value > 180) { throw new ArgumentOutOfRangeException("Longitude must be between -180 and 180 degrees inclusive."); } this._lng = value; } } }

Download Source Code

Demo

Conclusion

I hope you liked this article based on how to implement latitude and longitude validation in JavaScript and C#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

You may also like: