Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate an input field if value is not null in Laravel

I am trying to create and update users with laravel 5.4

This is the validation added for create user. It works.

$this->validate($request, [
    'name' => 'required|max:255',
    'email' => 'required|email|max:255|unique:users',
    'password' => 'required|min:6|confirmed',
]);

On update the password field is not required. But validate the min:6 and confirmed rule if the password field is not null. Tried with sometimes.. but not working..

$this->validate($request, [
    'name' => 'required|max:255',
    'email' => 'required|email|max:255|unique:users,email,'.$id,
    'password' => 'sometimes|min:6|confirmed',
]);
like image 313
noufalcep Avatar asked Mar 29 '17 05:03

noufalcep


People also ask

How do you check if a field is NULL in validation rule?

The Validation Rule contains ISNULL(TEXT(Picklist_Field__c)). ISNULL determines if an expression is null (blank) and returns TRUE if it is. If it contains a value, this function returns FALSE.

IS NOT NULL function in laravel?

Check if not null: whereNotNullSELECT * FROM users WHERE last_name IS NOT NULL; The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull method, which allows you to verify if a specific column's value is not NULL .

How do you add a validation rule in laravel?

You should add all your validation logic in the passes() function. It should return true or false based on the logic you have written in the function. The message() function returns a string that specifies the error message to be displayed in case the validation fails.


2 Answers

try using nullable as a rule

'password' => 'nullable|min:6|confirmed',

see https://laravel.com/docs/5.8/validation#a-note-on-optional-fields

like image 120
Rejinderi Avatar answered Nov 09 '22 00:11

Rejinderi


In case column is nullable

'password' => 'nullable|min:6|confirmed',

@Rejinderi's answer is correct!

In case column is not nullable (This may help other)

'password' => 'sometimes|required|min:6|confirmed',

Result

username = 'admin',
password = null // fail- required

username = 'admin',
password = 123 // fail- min:6

username = 'admin' // pass- validate only exist
like image 36
C.V Avatar answered Nov 09 '22 02:11

C.V