You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击按钮时若日期校验弹出alert_box则阻止第二个函数执行的实现方法

解决方案

1. 修改日期校验函数,增加布尔返回值

原来的date_control仅在校验失败时无值返回,没有明确的校验状态标识,我们需要让它校验失败时返回false,校验通过时返回true,同时补全日期格式非法的校验逻辑,避免匹配失败时报错:

function date_control(beginTs,endTs){
    // 先判断是否有日期为空
    if (!beginTs.length || !endTs.length) {
        show_alertbox('One of the two dates is empty please enter the start and end date');
        return false;
    }
    // 校验日期格式是否合法
    var tabDeb = beginTs.match(/^(\d+)-(\d+)-(\d+) (\d+)\:(\d+)$/);
    var tabFin = endTs.match(/^(\d+)-(\d+)-(\d+) (\d+)\:(\d+)$/);
    if (!tabDeb || !tabFin) {
        show_alertbox('日期格式不正确,请按照 YYYY-MM-DD HH:mm 格式输入');
        return false;
    }
    // 转换日期比较大小
    var beginDate = new Date(tabDeb[3], tabDeb[2] - 1, tabDeb[1], tabDeb[4], tabDeb[5]);
    var endDate = new Date(tabFin[3], tabFin[2] - 1, tabFin[1], tabFin[4], tabFin[5]);
    if (beginDate > endDate) {
        show_alertbox('Start date is greater than the end date');
        return false;
    }
    // 所有校验通过返回true
    return true;
}

2. 修改按钮的点击逻辑

在onclick中增加判断,仅当校验函数返回true(校验通过)时,才执行后续的AJAX调用函数:

<button type="button" class="" onclick="javascript:
        if(date_control($('#{$dateSId}').val(),$('#{$dateFId}').val())){
            call_Js($('#{$dateSId}').val(),$('#{$dateFId}').val());
        }">search by date 
</button>

补充优化说明

  • 补全了日期格式非法的校验逻辑,避免正则匹配失败后访问数组下标抛出JS错误
  • 给日期变量增加了var声明,避免污染全局作用域
  • 原有功能逻辑完全保留,仅增加了校验状态的判断链路

内容的提问来源于stack exchange,提问作者messoaud Rostane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 09:09:01