JavaScript如何校验数组对象起止年份并在非法时提醒用户
实现方案
完全可以通过新增年份校验逻辑实现需求,具体操作如下:
核心校验逻辑说明
由于你代码中的startyearValue和endyearValue可能为字符串类型,校验时需要先转换为数字再比较大小,避免字符串按字符顺序比较产生的异常。使用数组some()方法遍历校验,只要存在任意一项不符合要求就立即返回校验不通过,性能更优。修改后的完整点击事件代码
$('#jqxbutton').click(function () { var rows = $('#jqxgrid').jqxGrid('getrows'); var selectedRows = rows.filter(x => x.available) for(let i = 0; i < selectedRows.length; i++) { if (selectedRows[i].yeareligible === "N" && selectedRows[i].startyearValue === null && selectedRows[i].endyearValue === null ) { selectedRows[i].startyearValue = -1; selectedRows[i].endyearValue = -1; } else if (selectedRows[i].yeareligible === "Y" && selectedRows[i].startyearValue === null && selectedRows[i].endyearValue === null ) { selectedRows[i].startyearValue = '2015'; selectedRows[i].endyearValue = '2021'; } } console.log(selectedRows); // 新增年份校验逻辑 const hasInvalidYear = selectedRows.some(item => { const start = Number(item.startyearValue); const end = Number(item.endyearValue); return start > end; }); // 校验不通过则弹出提示,终止后续逻辑 if (hasInvalidYear) { alert("Some of your selections have start year greater than end year, please check and make sure start year is always less than end year"); $('#jqxgrid').jqxGrid('clearselection'); return; } // 校验通过后再执行原有后续逻辑、发送Ajax请求 $('#jqxgrid').jqxGrid('clearselection'); // 此处写你的Ajax调用代码 //var selectedRows = $('#jqxgrid').jqxGrid('getselectedrowindex'); //checkIfThereAreSelectedRows(selectedRows); });
- 效果验证
你给出的示例数据中第一项startyearValue=2012、endyearValue=2010,经过校验后会触发弹窗提示,不会执行后续的Ajax发送逻辑,完全符合你的需求。
内容的提问来源于stack exchange,提问作者user16776772
相关产品推荐
相关产品推荐

