需要使用JavaScript限制输入时序

时间:2017-05-17 08:10:22

标签: javascript

我有两个文本框,它们在结构“01:00 Am”中“从时间”和“到时间”。

我的要求是,如果用户输入的时间超过15小时,则时间不应超过15小时(意味着不应超过“04:00 pm”)在第二个文本框中15小时它应该显示错误。请给我建议如何在javascript中完成?

1 个答案:

答案 0 :(得分:0)

我自己开发了它。在不使用日期/时间对象的情况下正常工作。

function validateTimeDiff() {

    var startTime = document.getElementById("txt_StartTime").value;
    var endTime = document.getElementById("txt_Endtime").value;

    var startHours = parseInt(startTime.substring(0, 2));
    var endHours = parseInt(endTime.substring(0, 2));

    var startMeridian = startTime.substring(6, 8).toUpperCase();
    var endMeridian = endTime.substring(6, 8).toUpperCase();

    var startMin = parseInt(startTime.substring(3, 5));
    var endMin = parseInt(endTime.substring(3, 5));
    var minsDiff = endMin - startMin;


    if (startHours != 12 && startMeridian == "PM") {
        startHours = startHours + 12;
    }

    if (endHours != 12 && endMeridian == "PM") {
        endHours = endHours + 12;
    }

    if (startHours == 12 && startMeridian == "AM") {
        startHours = 0;
    }

    if (endHours == 12 && endMeridian == "AM") {
        endHours = 0;
    }

    var startCount = 24 - startHours;
    var endCount = 24 - endHours;

    if (startHours == 12 || endHours == 12) {
        if (startHours > endHours) {
            var hourDiff = startHours + endHours;
        }
        else
            var hourDiff = endHours - startHours;
    }

    if (startHours > 12 || endHours > 12) {
        if (startHours > endHours) {
            var hourDiff = startCount + endHours;
        }
        else
            var hourDiff = startCount - endCount;
    }

    if (startHours > 12 || endHours < 12) {
        if (startHours > endHours) {
            var hourDiff = startCount + endHours;
        }
        else
            var hourDiff = startCount - endCount;
    }

    if (hourDiff > 15) {
       alert("End time shouldn't exceed more than 15hrs");

        return false;
    }

    if (hourDiff >= 15 && minsDiff > 0) {
        alert("End time shouldn't exceed more than 15hrs");
        return false;
    }

    return true;
}