heihachi88
6/26/2014 - 4:45 PM

Custom rules in validation service. Implementing "alpha_spaces" rule in this example (letters and white spaces). Don't forget to add service

Custom rules in validation service. Implementing "alpha_spaces" rule in this example (letters and white spaces). Don't forget to add service provider in app.php array!

// app/lang/ru/validation.php
// applying custom rule message for title field

'custom' => array(
    'title' => array(
        'alpha_spaces' => 'Поле :attribute может содержать только буквы и пробелы.',
    ),
),
namespace Validation;

class CustomValidator extends \Illuminate\Validation\Validator {

	public function validateAlphaSpaces($attribute, $value, $parameters) {
		if (preg_match('/^[\pL\s]+$/u', $value)) {
			return true;
		}

		return false;
	}
}
namespace Validation;
 
use Illuminate\Support\ServiceProvider;
 
class ValidatorServiceProvider extends ServiceProvider {

	public function register() {
	// nothing yet
	}
 
	public function boot() {
		$this->app->validator->resolver(function($translator, $data, $rules, $messages) {
			return new CustomValidator($translator, $data, $rules, $messages);
		});
	}

}