Переглянути джерело

Create validation rule MaxMultiLine and add it to the validation in ContactController

Yoaz 2 роки тому
батько
коміт
b228f0eea1

+ 2 - 1
app/Http/Controllers/ContactController.php

@@ -6,6 +6,7 @@ use Illuminate\Http\Request;
 use Auth;
 use App\Contact;
 use App\Jobs\ContactPipeline\ContactPipeline;
+use App\Rules\MaxMultiLine;
 
 class ContactController extends Controller
 {
@@ -21,7 +22,7 @@ class ContactController extends Controller
 		abort_if(!Auth::check(), 403);
 
 		$this->validate($request, [
-			'message' => 'required|string|min:5|max:500',
+			'message' => ['required', 'string', 'min:5', new MaxMultiLine('500')],
 			'request_response' => 'string|max:3'
 		]);
 

+ 34 - 0
app/Rules/MaxMultiLine.php

@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Rules;
+
+use Illuminate\Support\Str;
+use Illuminate\Contracts\Validation\InvokableRule;
+
+class MaxMultiLine implements InvokableRule
+{
+    private $maxCharacters;
+
+    public function __construct($maxCharacters)
+    {
+        $this->maxCharacters = $maxCharacters;
+    }
+
+    /**
+     * Run the validation rule.
+     *
+     * @param  string  $attribute
+     * @param  mixed  $value
+     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
+     * @return void
+     */
+    public function __invoke($attribute, $value, $fail)
+    {
+        $realCount = Str::length($value) - Str::substrCount($value, "\r\n");
+
+        if($realCount > $this->maxCharacters)
+        {
+            $fail('validation.max.string')->translate(['max' => $this->maxCharacters]);
+        }
+    }
+}