dtq81142 2017-01-23 11:42
浏览 435

Laravel验证规则如果字段为空,则需要另一个字段

I have a Laravel 5.3 app, and an update form where I send user profile values. One of them is user image as well, I am creating a hidden input field for it, so if the user is not uploading any new image, I can still see that he has the hidden field with the old image value.

<input type="hidden" class="form-control" name="old_image" value="{{ $player->image_filename }}" id="oldImage">

If he removes the image, the hidden input value becomes empty.

document.getElementById('oldImage').value = '';

That is how I thought of updating a user image. But I don't know how to set up validation rules for that form. Something that would be similar to this:

    public function rules()
    {
        return [
          'first_name' => 'required|max:50',
          'last_name' => 'required|max:50',
          'birthday' => 'required',
          'image' => required if old_image empty
        ];
    }

I have tried with 'image' => 'required_without:old_image', and also with 'image' => 'required_if:old_image, null', but none of them showed any error message for missing image. I am showing error messages like this:

  • 写回答

3条回答 默认 最新

  • doufang7385 2017-01-23 12:03
    关注

    Try this

    if (empty($request->input('old_image'))){
         $this->validate($request, [
           'image' => 'required',
         ]);
    }
    else {
         // Validation in case of else goes here
         $this->validate($request, [
          // rule
         ]);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度