2
votes

How can i make a custom validation rule to an input which value must be an integer and starting with 120? I already read about making custom messages but didnt understand about rules. I want to use a regex to validate the data. ^120\d{11}$ here is my regex. I'm new in Laravel that's why cant now imagine how to do that.

A custom validation to use it in $this->validate($request, []);

Now i'm validating data like so:

$this->validate($request, [
    'user_id' => 'integer|required',
    'buy_date' => 'date',
    'guarantee' => 'required|unique:client_devices|number',
    'sn_imei' => 'required|unique:client_devices',
    'type_id' => 'integer|required',
    'brand_id' => 'integer|required',
    'model' => 'required'
]);

The input that i want to add custom validation is guarantee

3

3 Answers

1
votes

The quickest neatest way is an inline validator in your controller action:

public function store(Request $request)
{

    $validator = Validator::make($request->all(), [
        'number' => [
            'regex' => '/^120\d{11}$/'
        ],
    ]);

    if ($validator->fails()) {
        return redirect('post/create')
            ->withErrors($validator)
            ->withInput();
    }

    return view('welcome');
}

Where number is the name of the field being submitted in the request.

If you have a lot of validation to do, you might want to consider using a Form Request instead, as a way of consolidating a lot of validation logic.

1
votes

You can create custom validations in your controller as:

$name = Input::get('field-name')

$infoValidation = Validator::make( 
                    array( // Input array
                        'name'  => $name,

                    ),
                    array( // rules array
                        'name'  => array("regex:/^120\d{11}$"),
                    ),

                    array( // Custom messages array
                        'name.regex' => 'Your message here',
                    )
                ); // End of validation

                $error = array();
                if ($infoValidation->fails())
                {
                    $errors =  $infoValidation->errors()->toArray();
                    if(count($errors) > 0)
                    {
                        if(isset($errors['name'])){
                            $response['errCode'] = 1;
                            $response['errMsg']  = $errors['name'][0];
                        }

                    }
                    return response()->json(['errMsg'=>$response['errMsg'],'errCode'=>$response['errCode']]);
                }

Hope this helps.

0
votes

Since Laravel 5.5, you can make the validation directly on the request object.

public function store(Request $request)
{
    $request->validate([
        'guarantee' => 'regex:/^120\d{11}$/'
    ]);
}