Odin Thunder
Odin Thunder

Reputation: 3547

Laravel validation rule "URL" does not pass empty value

I have input text field whith validation rule :

public function rules()
{
    return [
        'field' => 'url',
    ];
}

It`s not required (field can be empty) but validation return an error.

Upvotes: 7

Views: 8813

Answers (4)

When you use formData (js) to submit your request, "null" is assigned by default for all empty fields. This will pass through Laravel "nullable" validaton and indicate as invalid input. So, please, use something like below in your validation rules.

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [];
        if($this->filled('field') && $this->field!= 'null'){
            $rules['field'] = 'url';
        }
        return $rules;
    }

In order to do this use laravel's form requests. https://laravel.com/docs/8.x/validation#creating-form-requests

Upvotes: 0

pilishen
pilishen

Reputation: 21

when we submmitting values from js, like through a FormData, the value null could be submitted as string containing 'null', which may pass a nullable rule, cause further type check fail. so be sure to make this value be posted as '', literaly nothing, no a 'null' string

Upvotes: 2

Odin Thunder
Odin Thunder

Reputation: 3547

Solve problem use "nullable":

public function rules()
{
    return [
        'field' => 'nullable|url',
    ];
}

Upvotes: 26

thefallen
thefallen

Reputation: 9749

Add sometimes rule to the validation. This means to validate it for a URL when the value is not given or null.

public function rules()
{
    return [
       'field' => 'sometimes|url',
    ];
}

Upvotes: 0

Related Questions