I want to make a custom validation rule. My model looks like this at the moment:
protected $rules = array(
'first_name' => 'required',
'last_name' => 'required',
'ssn' => 'required|integer|min:4|max:4',
'email' => 'required|email',
'dob' => 'required|checkAge',
'phone' => 'required',
'street' => 'required',
'postal_code' => 'required|integer|min:4',
'city' => 'required'
);
But where I have to put the custom validation rule? I have read that I need to extend it Validator. For this I've created a simple function
Validator::extend('foo', function($attribute, $value, $parameters)
{
return $value == 'foo';
});
And I don't know where I have to check it?
Maybe someone can help me.
Thanks
I do it by creating a validation folder in /app with any custom validation files in there.
I autoload this by editing app/start/global.php.
ClassLoader::addDirectories(array(
app_path() . '/commands',
app_path() . '/controllers',
app_path() . '/models',
app_path() . '/presenters',
app_path() . '/validation',
app_path() . '/database/seeds',
));
I also register the resolver in this file;
Validator::resolver(function($translator, $data, $rules, $messages) {
return new CoreValidator($translator, $data, $rules, $messages);
});
A sample custom validator class (in the validation folder);
<?php
class CoreValidator extends Illuminate\Validation\Validator
{
protected $implicitRules = array('Required', 'RequiredWith', 'RequiredWithout', 'RequiredIf', 'Accepted', 'RequiredWithoutField');
public function __construct(\Symfony\Component\Translation\TranslatorInterface $translator, $data, $rules, $messages = array())
{
parent::__construct($translator, $data, $rules, $messages);
$this->isImplicit('fail');
}
public function validatePostcode($attribute, $value, $parameters = null)
{
$regex = "/^((GIR 0AA)|((([A-PR-UWYZ][0-9][0-9]?)|(([A-PR-UWYZ][A-HK-Y][0-9][0-9]?)|(([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY])))) [0-9][ABD-HJLNP-UW-Z]{2}))$/i";
if (preg_match($regex, $value)) {
return true;
}
return false;
}
}
And add the custom error message to the array in in app/lang/en/validation.php
return array(
...
"postcode" => "Invalid :attribute entered.",
...
)
Extensions can be added as soon as the application boots. What I do is to create a validations.php
file in the same level of routes.php
and filters.php
and then add this to my app/start/global.php
:
require app_path().'/filters.php'; /// this one is already there...
require app_path().'/validations.php';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With