How can I re-utilise existing validation methods in my custom validation method in Laravel? -
let's have following custom validator:
<?php namespace app\providers; use illuminate\support\serviceprovider; use illuminate\support\facades\validator; class appserviceprovider extends serviceprovider { /** * bootstrap application services. * * @return void */ public function boot() { validator::extend('email_and_mx_record', function ($attribute, $value, $parameters, $validator) { //... }); } /** * register service provider. * * @return void */ public function register() { // } }
as implied validation name, want create mx record validation of email address. first thing first though, checking email address format valid. know simple enough if copy existing validation logic validator
class uses known function:
<?php namespace illuminate\validation; class validator implements validatorcontract { /** * validate attribute valid e-mail address. * * @param string $attribute * @param mixed $value * @return bool */ protected function validateemail($attribute, $value) { return filter_var($value, filter_validate_email) !== false; } }
but in ideal world, want stick dry principle.
i wondering if there way call method within custom validator or not? e.g. (doesn't work): return $validator->validateemail($attribute, $value) ? (do validation) : false;
.
the solution question way not repeat myself, , piggy-back on laravel email validator. now, copy existing logic.
if possible this, pave way me enhance other validation methods, isn't issue of being pedantic.
instead of calling laravel email validation function inside custom validation, i'm wondering why can't use email
rule rule only. there no need of overriding.
for example :
$this->validate($request, [ 'email' => 'bail|email|email_and_mx_record', ... ]);
bail
documentation :
sometimes may wish stop running validation rules on attribute after first validation failure. so, assign bail rule attribute:
Comments
Post a Comment