Validating latitude/longitude in Laravel validation regex rule - preg_match(): No ending delimiter '/' found [duplicate]
Asked Answered
B

1

18

I am trying to validate latitude/longitude in Laravel 5.4 project with custom regex rule (based on this answer: https://mcmap.net/q/496928/-php-validate-latitude-longitude-strings-in-decimal-format)

// Create validation
$validator = Validator::make($request->all(), [
    // ...
    'lat' => 'required|regex:/^[-]?(([0-8]?[0-9])\.(\d+))|(90(\.0+)?)$/',
    'long' => 'required|regex:/^[-]?((((1[0-7][0-9])|([0-9]?[0-9]))\.(\d+))|180(\.0+)?)$/'
], [
    'lat.regex' => 'Latitude value appears to be incorrect format.',
    'long.regex' => 'Longitude value appears to be incorrect format.'
]);

// Test validation
if ($validator->fails()) {
    return redirect()
        ->back()
        ->withErrors($validator)
        ->withInput();
}

When this runs, I am getting the following error:

preg_match(): No ending delimiter '/' found

I've tried this also;

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

Now I get this error:

preg_match(): No ending delimiter '^' found

What is the correct syntax to validate lat/lng in laravel via custom regex rule?

Beauregard answered 8/11, 2017 at 16:13 Comment(2)
Looks like you have to use an array?Drink
It might be more simple to validate by range like: 'lat' => 'between:-87,89', 'long' => 'between:-180,180',Shogun
O
28

Is it possible that the pipes are the problem? See, for example, Laravel 5.4 - Validation with Regex. I see that your regexp has a pipe character in it. Try separating the rules into an array instead of using the pipe here: required|regex

In the second example, the first ^ is interpreted as the character that starts the regex string, so it expects a final ^ to match it.

Oxcart answered 8/11, 2017 at 16:21 Comment(2)
It was the pipe problem, i've solved it like this: 'lat' => ['required','regex:/^[-]?(([0-8]?[0-9])\.(\d+))|(90(\.0+)?)$/'], 'long' => ['required','regex:/^[-]?((((1[0-7][0-9])|([0-9]?[0-9]))\.(\d+))|180(\.0+)?)$/']Beauregard
The above regex is confirmed working for coordinate validation, thanks!Panteutonism

© 2022 - 2024 — McMap. All rights reserved.