Jul 9, 2017

Laravel5 -> Creating/Understanding Custom Validation.

Main goal to create our own validation and set message associated to our validation.

*

Implented the validation rule

$RULES = ['name' => 'required|myrule'];
Vaidator::make($ARRAY_DATA, $RULES);

*

Create custom rule. In app/Providers/AppServiceProvider.php add code below on boot function.

//  Create  your custome valitor
Validator::extend('myrule', function($attr $value, $params) {
    return ((rand(10,100)%2) == 0); // Random return failed/Pass
},
"validation.myrule"
);

// Create the  message rule message.
Validator::replacer('myrule', function($msg, $attr, $rule, $params) {
    return trans($message, ['attribute'=> $attribute]);
});

*

Create the rule message. Add entry on resources/lang/en/validation.php.


return [

'myrule' => 'Your :attribute got error.',

'custom' => [
  //  Your also add here, to override the message above for the specific file.
  // This not need unless you want some validation on specific field.
  'fieldname' => [
     'rulename' => ' This just sample custom my rule message',
   ],

  'name' => [
     'myrule' => 'My custom :attribute message override.',
   ]

]
];

No comments: