pwnz22 pwnz22 - 1 year ago 76
PHP Question

Laravel custom validation rule

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.

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

Answer Source

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')

    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.