在Laravel控制器中进行与其他字段的日期验证

huangapple go评论61阅读模式
英文:

Date validation with another fields in controller in Laravel

问题

如果 type =2,则 ldate 应大于 $eldate

英文:

Here is my validation code in the controller

 $eldate = Carbon::now()->addDay(4)->format('Y-m-d');

 $validatedData = $this->validate($request, [
        'ldate' => 'required|date|unique:leaves,ldate,NULL,employee,employee,'.auth()->id(),
        'ldate2'      => 'nullable|date|after_or_equal:ldate',
        'type' => 'required'
    ]);

In this validation code I have to add one more condition for date1

If type =2 then ldate should be greater than $eldate

答案1

得分: 1

使用自定义验证规则来解决此问题

$eldate = Carbon::now()->addDay(4);

$validatedData = $this->validate($request, [
    'ldate' => ['required', 'date', 'unique:leaves,ldate,NULL,employee,employee,' . auth()->id(), function (string $attribute, mixed $value, Closure $fail) use ($request, $eldate) {
        if ($request->type == 2 && $eldate->gt($value)) {
            $fail("The {$attribute} is invalid.");
        }
    }],
    'ldate2' => 'nullable|date|after_or_equal:ldate',
    'type' => 'required'
]);

有关自定义验证规则的更多信息,请查看以下链接:

使用闭包

使用规则对象

英文:

use custom validation rules to solve the issue

$eldate = Carbon::now()->addDay(4);

     $validatedData = $this->validate($request, [
            'ldate' => ['required','date','unique:leaves,ldate,NULL,employee,employee,'.auth()->id(), function (string $attribute, mixed $value, Closure $fail) use ($request, $eldate) {
                if ($request->type==2 && $eldate->gt($value)) {
                    $fail("The {$attribute} is invalid.");
                }
            }],
            'ldate2'      => 'nullable|date|after_or_equal:ldate',
            'type' => 'required'
        ]);

For custom validation rules

Using Closures

Using Rule Objects

答案2

得分: 1

如果您正在使用Laravel Form Request,则只需添加

    public function rules()
    {
        $eldate = Carbon::now()->addDay(4)->format('Y-m-d');
        $rules = [
            'ldate' => ['required', 'date', Rule::unique('leaves', 'ldate')->where(function ($query) {
                return $query->where('employee', auth()->id());
            })],
            'ldate2' => 'nullable|date|after_or_equal:ldate',
            'type' => 'required',
        ];
    
        if ($this->input('type') == 2) {
            $rules['ldate'][] = 'after:' . $eldate;
        }
    
        return $rules;
    }
英文:

If you're using Laravel Form Request, then simply add

public function rules()
{
    $eldate = Carbon::now()->addDay(4)->format('Y-m-d');
    $rules = [
        'ldate' => ['required', 'date', Rule::unique('leaves', 'ldate')->where(function ($query) {
            return $query->where('employee', auth()->id());
        })],
        'ldate2' => 'nullable|date|after_or_equal:ldate',
        'type' => 'required',
    ];

    if ($this->input('type') == 2) {
        $rules['ldate'][] = 'after:' . $eldate;
    }

    return $rules;
}

答案3

得分: 0

我可以展示如何使用自定义类,你可以在此处找到文档链接

控制器函数代码如下:

public function test(Request $request)
{
    $eldate = Carbon::now()->addDay(4);
    
    $rules = [
        'ldate'  => ['required', 'date', new ValidateDateTwo($eldate, $request->get('type'))],
        'ldate2' => ['nullable', 'date', 'after_or_equal:ldate'],
        'type'   => 'required'
    ];

    $validator = Validator::make($request->all(), $rules);

    if ($validator->fails()) {
        $messages = $validator->errors();
        $errors = [];
        foreach ($rules as $input => $rule) {
            foreach ($messages->get($input) as $key => $message) {
                $errors[$input] = $message;
            }
        }

        return Response::json(['status' => false, 'errors' => $errors]);

    }

    return response()->json([
        'status' => 'success',
        'data' => [
            'ldate' => $request->get('ldate'),
            'ldate2' => $request->get('ldate2'),
            'type' => $request->get('type')
        ]
    ]);
}

验证类如下:

<?php

namespace App\Http\Controllers;

use Illuminate\Contracts\Validation\Rule;

class ValidateDateTwo implements Rule
{


    /**
     * @var mixed
     */
    private $eldate;
    /**
     * @var mixed
     */
    private $type;

    public function __construct($eldate, $type)
    {
        $this->eldate = $eldate;
        $this->type = $type;
    }
    public function passes($attribute, $value)
    {
        return $this->type != 2 || !$this->eldate->gt($value);
    }


    public function message()
    {
        return 'Your error message.';
    }
}

我已经为你测试过了。

英文:

I can show how to use Custom Class
documentation: https://laravel.com/docs/10.x/validation#custom-validation-rules

controller function code

public function test(Request $request)
    {
        $eldate = Carbon::now()-&gt;addDay(4);
        
        $rules = [
            &#39;ldate&#39;  =&gt; [&#39;required&#39;, &#39;date&#39;, new ValidateDateTwo($eldate, $request-&gt;get(&#39;type&#39;))],
            &#39;ldate2&#39; =&gt; [&#39;nullable&#39;, &#39;date&#39;, &#39;after_or_equal:ldate&#39;],
            &#39;type&#39;   =&gt; &#39;required&#39;
        ];

        $validator = Validator::make($request-&gt;all(), $rules);

        if ($validator-&gt;fails()) {
            $messages = $validator-&gt;errors();
            $errors = [];
            foreach ($rules as $input =&gt; $rule) {
                foreach ($messages-&gt;get($input) as $key =&gt; $message) {
                    $errors[$input] = $message;
                }
            }

            return Response::json([&#39;status&#39; =&gt; false, &#39;errors&#39; =&gt; $errors]);

        }


        return response()-&gt;json([
            &#39;status&#39; =&gt; &#39;success&#39;,
            &#39;data&#39; =&gt; [
                &#39;ldate&#39; =&gt; $request-&gt;get(&#39;ldate&#39;),
                &#39;ldate2&#39; =&gt; $request-&gt;get(&#39;ldate2&#39;),
                &#39;type&#39; =&gt; $request-&gt;get(&#39;type&#39;)
            ]
        ]);
    }

And the Validation Class

&lt;?php

namespace App\Http\Controllers;

use Illuminate\Contracts\Validation\Rule;

class ValidateDateTwo implements Rule
{


    /**
     * @var mixed
     */
    private $eldate;
    /**
     * @var mixed
     */
    private $type;

    public function __construct($eldate, $type)
    {
        $this-&gt;eldate = $eldate;
        $this-&gt;type = $type;
    }
    public function passes($attribute, $value)
    {
        return $this-&gt;type != 2 || !$this-&gt;eldate-&gt;gt($value);
    }


    public function message()
    {
        return &#39;Your error message.&#39;;
    }
}

i have tested it for you.

huangapple
  • 本文由 发表于 2023年6月6日 15:28:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76412318.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定