如何在Laravel中提交表单时设置自定义错误消息并防止重定向?

问题描述

这是表格。如果日期范围大于1年,则需要阻止此表单与消息(类似于表单中无效条目的消息)一起提交。或者也许我们只是不允许用户输入大于1年的日期范围。

<form role="form" action="#" method="POST">
    @csrf
    <div class="col-sm-1">
        <label for="startdate" class="form-control">From:</label>
    </div>
    <div class="col-sm-2">
        <input type="date" name="startdate" class="form-control">
    </div>
    <div class="col-sm-1">
        <label for="enddate" class="form-control">To:</label>
    </div>
    <div class="col-sm-2">
        <input type="date" name="enddate" class="form-control">
    </div>
    <div class="col-sm-1">
        <button type="submit" class="form-control btn btn-primary">Filter</button>
    </div>
</form>

日期范围不得超过一年。

解决方法

您可以使用javascript来验证日期差是否超过一年。完成后,将其交给您的控制器。为此发出警告,指出日期差不应超过一年

第二,在带有type = "date"的输入表单中,有一个名为max的字段选项,可用于显示日历<input type="date" max="2021-07-08"/>中的最大日期。当enddate

时使用该值来设置startdate is input

第三,放置逻辑以验证控制器内部的日期差异以及安全性

<script>
function callstart() {
    startdate = document.getElementById("startdate").value
    currentDate = new Date(startdate)
    var newDate = new Date();
    newDate.setDate(currentDate.getDate()+365);

    var year = newDate.getFullYear()
    var month = ("0" + (newDate.getMonth() + 1)).slice(-2)
    var date = ("0" + newDate.getDate()).slice(-2)
   
   // Write min date after a year in end date input form
    document.getElementById("enddate").max = year + "-" + month + "-"+ date
    
}

function callend(){

    var enddate = document.getElementById("enddate").value

    // validate if the date difference is more than a year

    const diffTime = Math.abs(new Date(enddate) - new Date(startdate));
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
    if(diffDays > 365){
        alert("date difference should not be greater than a year")
    }
}

</script>

<form role="form" action="{{ route('admin.report') }}" method="POST">
    @csrf
    <div class="col-sm-1">
        <label for="startdate" class="form-control">From:</label>
    </div>
    <div class="col-sm-2">
        <input type="date" name="startdate" class="form-control" placeholder="Date"  onchange="callstart()" id="startdate">
    </div>
    <div class="col-sm-1">
        <label for="enddate" class="form-control">To:</label>
    </div>
    <div class="col-sm-2">
        <input type="date" name="enddate" placeholder="Date"  onchange="callend()" id="enddate" max="">
    </div>
    <div class="col-sm-1">
        <button type="submit" class="form-control btn btn-primary">Filter</button>
    </div>
</form>