2

I have custom regex for validation user profile url in social sites:

/(?:https:\/\/)?(?:http:\/\/)?(?:www\.)?(?:ok|odnoklassniki)\.ru\/(?:\w*#!\/)?([\w-]*)/

See demo here.

Code:

if(isset($request->odnoklassniki)) {
    $this->validate($request, [
        'odnoklassniki' => 'regex:/(?:https:\/\/)?(?:http:\/\/)?(?:www\.)?(?:ok|odnoklassniki)\.ru\/(?:\w*#!\/)?([\w-]*)?/'
    ], ['regex' => 'Enter correct url to your profile in this website']);
    $candidate->odnoklassniki = $request->odnoklassniki;
    $candidate->save(); 
}

Error message:

preg_match(): No ending delimiter '/' found

Regex work successfully in my php code:

$re = '/(?:https:\/\/)?(?:http:\/\/)?(?:www\.)?(?:ok|odnoklassniki)\.ru\/(?:\w*#!\/)?([\w-]*)/m';
$str = 'https://www.odnoklassniki.ru/username

http://odnoklassniki.ru/username

ok.ru/username
';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
echo "<pre>";
    print_r($matches);
echo "</pre>";

Result:

Array
(
    [0] => Array
        (
            [0] => https://www.odnoklassniki.ru/username
            [1] => username
        )

    [1] => Array
        (
            [0] => http://odnoklassniki.ru/username
            [1] => username
        )

    [2] => Array
        (
            [0] => ok.ru/username
            [1] => username
        )

)

1 Answer 1

3

The pipe character "|" has special function in the validation, it separates your validation rules, e.g.:

$validatedData = $request->validate([
    'title' => 'required|unique:posts|max:255'
]);

But since your regex validation includes the pipe character, you can use the other method of declaring validation rules

$validatedData = $request->validate([
    'title' => [
        'required',
        'unique:posts',
        'max:255'
    ]
]);

So this is the solution to your problem:

if(isset($request->odnoklassniki)) {
    $this->validate($request, [
        'odnoklassniki' => [
            'regex:/(?:https:\/\/)?(?:http:\/\/)?(?:www\.)?(?:ok|odnoklassniki)\.ru\/(?:\w*#!\/)?([\w-]*)?/'
        ]
    ], ['regex' => 'Enter correct url to your profile in this website']);
    $candidate->odnoklassniki = $request->odnoklassniki;
    $candidate->save(); 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, @aceraven777

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.