Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lumen Custom Validation

I am trying to implement a custom validation rule within lumen and I am following the docs for lumen 5.6. It says to refer to laravel validation to see how to use the validation. I am currently trying to make a validation to check if the value is a true null or not. So $x === "" would mean it fails Here is my rule located in App\Rules folder I created.

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class TrueNull implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if($value === "") {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute cannot be an empty string.';
    }
}

I copied this straight from lumen docs and make my modification to the passes function. Within my modal have

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
use App\Rules\TrueNull;
use Validator;

Then

public function validate($data)
{
    // make a new validator object
    $v = Validator::make($data, 
    [
        'x' => ['regex:/^(?=.+)(?:[1-9]\d*|0)?(?:\.\d+)?$/', new TrueNull]
    ]
}

But the validation for TrueNull never happens am I missing a connection or something its really frustrating because the docs says this should work. Here is my controller calling the update I am validating.

public function update(Request $request, $id)
    {
        /*
            In middleware need to add community id to request.
        */
        try {
            $site = Site::findOrFail($id);

            if ($site->validate($request->all())) {
                $site->fill($request->all());

                // save
                $site->save();
            } else {
                return response()->json($site->errors(), 422);
            }
        } catch (Exception $e) {
            return response()->json($e, 422);
        }

        return response()->json($site, 200);
    }
like image 825
Alexander Beyer Avatar asked Mar 29 '18 14:03

Alexander Beyer


3 Answers

For future reference I found a random snippet of code that offset the basic docs of Lumen. In my class for TrueNull instead of implements Rule I changed this to implements ImplicitRule and changed the use to \ImplicitRule and it is now catching that "" is not a null.

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\ImplicitRule;

class TrueNull implements ImplicitRule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if($value === "") {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute cannot be an empty string.';
    }
}
like image 177
Alexander Beyer Avatar answered Sep 30 '22 14:09

Alexander Beyer


The answer is greate by @Alexander Beyers but it doesn't work for Lumen 5.3. Here is how to create organised custom rules for the Lumen 5.3.

Create a Directory name Rules under app dir and Create the Following File:

namespace App\Rules;
use Illuminate\Support\Facades\Validator;

class AlphaSpace
{
    public static function validate(){
        //Extending the custom validation rule.
        Validator::extend('alpha_spaces', function ($attribute, $value) {
            // This will only accept alpha and spaces.
            // If you want to accept hyphens use: /^[\pL\s-]+$/u.
            return preg_match('/^[\pL\s]+$/u', $value);
        });
    }
}

Open the file resources/lang/en/validation and add the following under the Custom Validation: Note:(under the Custom Validation is only for maintenance)

/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'alpha_spaces' => 'The :attribute may only contain letters and spaces.',

Call the rule in app/Providers/AppServiceProvider::boot():

use HRM\Core\Rules\AlphaSpace;

class AppServiceProvider extends ServiceProvider
{
    public function boot() {
        AlphaSpace::validate();
    }

// class will carry on with the stuffs!

Now you can use it anywhere you want to like this:

'first_name' => 'required|alpha_spaces|min:3|max:50',
'last_name' => 'required|alpha_spaces|min:3|max:50',
like image 23
MKJ Avatar answered Sep 30 '22 12:09

MKJ


Version: Lumen 7.X

First, declare your rule in app/Providers/AppServiceProvider.php. Create a boot() with your rule method as following (I registered a rule for phone number).

public function register()
    {
        //
    }

    public function boot()
    {
        app('validator')->extend('phone', function ($attribute, $value) {
            return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
        });

        app('validator')->replacer('phone', function ($message, $attribute, $rule, $parameters) {
            return 'Phone number has wrong format.';
        });
    }

Different part in opposite of Laravel, and most important is, that AppServiceProvider is not registered in Lumen by default.

You need to go to bootstrap/app.php and uncomment following line:

 $app->register(App\Providers\AppServiceProvider::class);

Maybe you would like to do composer dumpautoload, just in case, but it should work without it.

Then, in your code:

$validator = Validator::make(
   $request->all(),
   [ 
       'tel' => 'required|phone' 
   ],
   [ 
       'tel.required' => 'Phone is required', 
       'tel.phone' => 'Phone has wrong format'
   ]
);

That should be it!

like image 21
MCFreddie777 Avatar answered Sep 30 '22 13:09

MCFreddie777