Skip to content

Instantly share code, notes, and snippets.

@PhillipMwaniki
Created October 10, 2023 08:26
Show Gist options
  • Save PhillipMwaniki/465dc3706813b0a4e17b60971babd307 to your computer and use it in GitHub Desktop.
Save PhillipMwaniki/465dc3706813b0a4e17b60971babd307 to your computer and use it in GitHub Desktop.
Laravel Longitude and Latitude Validation Rules
<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class LatitudeRule implements ValidationRule
{
/**
* Run the validation rule.
*
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$regex = '/^[-]?((([0-8]?[0-9])(\.(\d{1,8}))?)|(90(\.0+)?))$/';
if (! preg_match($regex, $value)) {
$fail('The :attribute must be a valid latitude coordinate in decimal degrees format.');
}
}
}
<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class LongitudeRule implements ValidationRule
{
/**
* Run the validation rule.
*
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$regex = '/^[-]?((((1[0–7][0–9])|([0–9]?[0–9]))(\.(\d{1,8}))?)|180(\.0+)?)$/';
if (! preg_match($regex, $value)) {
$fail('The :attribute must be a valid longitude coordinate in decimal degrees format.');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment