ruby_noobie
ruby_noobie

Reputation: 205

Field validation for phone number in Laravel 5?

I have the following array of fields:

$fields = [
    'name'     => [
        'label' => 'Company Name' . $req,

     ],
     'address1' => [
     'label' => 'Address' . $req
     ],
    'address2' => [
        'label' => 'Address (Line 2)'
     ],
    'zip'      => [
        'label' => 'Zip/Postal Code'
     ],

    'phone'   => [
        'label' => 'Office Phone',
        'val'   => dotted($active->office)
     ],
    [
        'type'  => 'submit',
        'label' => "Save",
        'class' => 'btn btn-primary !important'
    ]
];

I need to validate the field 'phone' to make sure that it is 10 digits, all numbers. What can I add here to check this here, or should I validate it somewhere else?

Upvotes: 0

Views: 3791

Answers (1)

Andrew Nolan
Andrew Nolan

Reputation: 2107

There are multiple ways you can go about validation using Laravel. Personally, I follow making a new Request class for what Model I am storing and type hint the request in the Controller function. This is my flow, but again, there are several ways to utilize Laravel validation. Below is an example. You would name the classes what you want.

From CLI

php artisan make:request StoreUserDataRequest

Within StoreUserDataRequest class have this function that has your validation rules for each field

public function rules()
    {
        $phonePattern = '/\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/';
        return [
            'name' => 'required|unique|max:255',
            'address1' => 'required',
            'address2' => 'required',
            'zip' => 'required',
            'phone' => 'required|regex:' . $phonePattern
        ];
    }

Within your controller method

  public function store(StoreUserDataRequest $request)
    {
        // do whatever if validation passes.
    }

When the store method is called, the parameters in the $request have to pass the validation rules or it fails. If you want to review the other validation techniques using laravel, go here

Upvotes: 1

Related Questions