Skip to content

2_5_Request validation

YMHuang edited this page Jul 26, 2016 · 1 revision

VMS receives a request in JSON format from a client. In order to getting appropriate request data, it SHOULD be validated the JSON format is correct, before retrieving the request in controller.

There is a rules() method for defining the validation rules. The rules() is applied to check request format before entering a controller.

For example, the following class is for volunteer registration. The rules() defines the format in Array type. It contracts username value must exists, not existing in volunteers table and the maximum length is 255.

<?php

class VolunteerRegistrationRequest extends AbstractJsonRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'username' => 'required|unique:volunteers|max:255',
            'password' => 'required|between:6,255|regex:/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/',
            'first_name' => 'required|max:255',
            'last_name' => 'required|max:255',
            'birth_year' => 'date_format:Y',
            'gender' => 'required|in:male,female,other',
            'city' => 'required',
            'city.id' => 'required|exists:cities,id',
            'location' => 'sometimes|required|string|max:255',
            'phone_number' => 'sometimes|required|max:255',
            'email' => 'required|email|unique:volunteers',
            'emergency_contact' => 'sometimes|required|max:255',
            'emergency_phone' => 'sometimes|required|string|max:255',
            'introduction' => 'max:255',
            'avatar' => 'sometimes'
        ];
    }
}

There are avaliable rules in Laravel Documentation.