2

I am trying to validate a field but I am not able to do it. I have this Request Validator

public function rules()
    {
        return  [            
            ...
            'input' => 'required|url|email',
        ];
    }

What I want to do is to validate if the input is url or email, can be one of them, what can I do? Here I am validating both cases, but the input can be one of them. Thanks.

2

1 Answer 1

1
public function rules(): array
{
    return [
        'input' => ['required', function ($field, $value) {
            $data = [$field => $value];
            $emailValidator = Validator::make($data, [$field => 'email']);
            $urlValidator = Validator::make($data, [$field => 'url']);

            if ($urlValidator->passes() || $emailValidator->passes()) {
                return true;
            }

            $this->validator->getMessageBag()->add($field, $field . ' must be a valid email address or a valid url');

            return false;
        }],
    ];
}
Sign up to request clarification or add additional context in comments.

Comments

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.