7

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.

2
  • show the error you get Commented Mar 21, 2017 at 10:20
  • i get an error from my messages function 'field.url' => 'error message ...' Commented Mar 21, 2017 at 10:24

4 Answers 4

26

Solve problem use "nullable":

public function rules()
{
    return [
        'field' => 'nullable|url',
    ];
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

can you be more specific and show a code example to resolve the error in this situation?
This is beyond the scope of server-side validation. I think we shouldn't be adding null values to FormData in the first place -- either it's specifically an empty string (per the user's input) or the value is absent/omitted altogether.
0

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',
    ];
}

1 Comment

don`t work ... In Laravel docs "run validation checks against a field only if that field is present in the input array". Field present in array but have an empty value.
0

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

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.