在 Laravel 验证正则表达式规则中验证纬度/经度 - preg_match():未找到结束分隔符“/”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47184526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:55:35  来源:igfitidea点击:

Validating latitude/longitude in Laravel validation regex rule - preg_match(): No ending delimiter '/' found

phpregexlaravellatitude-longitudelaravel-validation

提问by Latheesan

I am trying to validate latitude/longitude in Laravel 5.4 project with custom regex rule (based on this answer: https://stackoverflow.com/a/22007205/2332336)

我正在尝试使用自定义正则表达式规则验证 Laravel 5.4 项目中的纬度/经度(基于此答案:https://stackoverflow.com/a/22007205/2332336 )

// 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

preg_match(): 未找到结束分隔符“/”

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

preg_match(): 未找到结束分隔符 '^'

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

通过自定义正则表达式规则在 laravel 中验证纬度/经度的正确语法是什么?

回答by Martin Cook

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

有没有可能是管道有问题?例如,请参阅Laravel 5.4 - 使用正则表达式验证。我看到您的正则表达式中有一个管道字符。尝试将规则分成一个数组,而不是在这里使用管道: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.

在第二个示例中,第一个^被解释为开始正则表达式字符串的字符,因此它需要一个 final^来匹配它。