Πέμπτη, 6 Δεκεμβρίου 2018

Laravel Custom Validation "comma separated*

Do you need to validate that something is a comma separated string and each entry should be then validated that it is a valid email, phone etc?

Simply add the following in your  AppServiceProvider's boot function:

        Validator::extend('comma_separated', function ($attribute, $value, $parameters, $validator) {
            $entryRules = $parameters[0];
            $parts = explode(",", $value);
            if ($entryRules) {
                foreach ($parts as $part) {
                    $entryValidator = 
                        validator(
                            ["value" => $part], 
                            ["value" => $entryRules], 
                            [],  
                            ["value" => $validator->getDisplayableAttribute($attribute) . " > Value"]
                        );
                    if ($entryValidator->fails()) {
                        foreach ($entryValidator->errors()->getMessages() as $validationErrors) {
                            if (is_array($validationErrors)) {
                                foreach ($validationErrors as $validationError) {
                                    $validator->errors()->add($attribute, $validationError);
                                }
                            }
                            else {
                                $validator->errors()->add($attribute, $validationErrors);
                            }
                        }
                        return FALSE;
                    }
                }
            }
            return TRUE;
        });

And use it like in the following snippet:

    $something = "something";
    $validator = validator(["value" => $something], ["value" => "comma_separated:email"]);

In my project, I have defined it in the $rules of my model class:

    public static $rules = [
      "datetime_from" => "required|date",
      "datetime_to" => "required|date|after_or_equal:datetime_from",
      "attendees" => "required|comma_separated:email",
      "title" => "required|min:3|max:255",
      "description" => "max:2000",
    ];

LinkWithin

Blog Widget by LinkWithin

Mobile edition