How to do Latitude Longitude validation in Laravel?

Validating user input is one of the most important parts of application development. Latitude Longitude validation is one type of validation. We validate Latitude Longitude in applications that consists of locations, real-time travel data, navigations, GPRS, or map entries.

To get latitude and longitude inputs from users, we should assure that they are the correct entries. These are important values. As a slight variation in the digits entered can have huge effects. Therefore, this is sensitive data that we should validate properly.

We can define Laravel validation rules in the Controller class. The rules check values before saving or storing user data in the application and database. Validation rules can be applied to many types of inputs from a user.

There are separate rules for mobile numbersmaximum character validations, and image and video uploads. For example, checking image dimensions. Let’s check the rule to assure that entered data is acceptable for latitudes and longitudes.

Latitude Longitude validation rule

We can validate latitude and longitude entries using a regex pattern for each. The pattern for each is as below.

Latitude regex

'lat' => ['required', 'regex:/^[-]?(([0-8]?[0-9])\.(\d+))|(90(\.0+)?)$/'],

Longitude regex

'long' => ['required', 'regex:/^[-]?((((1[0-7][0-9])|([0-9]?[0-9]))\.(\d+))|180(\.0+)?)$/'],

We can add the above two patterns in the save / store function of the Controller class.

The two rules for ‘required’ and ‘regex check’ are passed for latitude and longitude values.