简体   繁体   English

在运行中验证和修改时间输入

[英]Validate and Modify Time Input on the Fly

In Javascript, how can I validate and modify the user time input using the regular expression and string.replace function so that instead of telling the user anything, it will validate and modify the input on the fly? 在Javascript中,如何使用正则表达式和string.replace函数验证和修改用户时间输入,以便不是告诉用户任何东西,它会动态验证和修改输入?

For example, the user input could be 1.12p 13:12 1,12PM , but the final result should always be 1:12 PM . 例如,用户输入可能是1.12p 13:12 1,12PM ,但最终结果应始终是1:12 PM

Does anyone have examples on how to do so? 有没有人有关于如何这样做的例子?

PS. PS。 I know that using timepicker is a way more efficient way, but I have to use the user input in this case 我知道使用timepicker是一种更有效的方式,但在这种情况下我必须使用用户输入

A simple regex you could use as a starting point: 一个简单的正则表达式,你可以用作一个起点:

(\d{1,2})\s*[.,:;]\s*(\d{1,2})\s*(([Aa]|[Pp])[Mm]?)?
^        ^  ^     ^  ^        ^  ^ ^         ^
Hour group  |     |  Minutes  |  | |         M is optional
         |  Valid separators  |  | Case-insensitivity
         |        |           |  AM/PM group
         ------------------------------Allow spaces

You'd still need to validate that the time is valid (59:99 is probably not valid), but this would at least make it easier to parse the string in javascript. 你仍然需要验证时间是否有效(59:99可能无效),但这至少可以更容易解析javascript中的字符串。 After you've parsed it, you can print it back out however you want. 在解析之后,您可以根据需要将其打印出来。

EDIT: Oops. 编辑:哎呀。 Forgot that javascript does not support named groups. 忘了javascript不支持命名组。 Just use numbered groups to the same effect. 只需使用编号组即可获得相同的效果。

EXAMPLE
What the hay... here's a complete working example. 什么干草...这是一个完整的工作示例。 When to validate (and what to do with invalid input) is left up to you: 何时验证(以及如何处理无效输入)由您决定:

<html>
    <head>
        <script>
function parseTime( timeString ){
    var timePattern = /(\d{1,2})\s*[.,:;]\s*(\d{1,2})\s*(([Aa]|[Pp])[Mm]?)?/;
    var timeMatch = timePattern.exec( timeString );

    var INVALID = null;

    if ( timeMatch !== null ){
        var hour = timeMatch[1];
        var minute = timeMatch[2];
        var ampm = timeMatch[3];

        if ( minute < 0 || minute > 59 )
            return INVALID;

        if ( ampm != "" ){
            if ( hour < 1 || hour > 12 )
                return INVALID;

            ampm = ampm.substring(0,1).toUpperCase() == "A" ? "AM" : "PM";
        } else {
            if ( hour > 23 )
                return INVALID;

            ampm = ( hour < 13 ? "AM" : "PM" );
            hour = hour % 12;
            if ( hour == 0 ) hour = 12;
        }

        return hour + ":" + minute + " " + ampm;
    } else {
        return INVALID;
    }
}

function unitTest(){
    var testStrings = [
        ["1:30 PM", "1:30 PM"],
        ["1.30p", "1:30 PM"],
        ["1;30a", "1:30 AM"],
        ["59:99 PM", null],
        ["0,30", "12:30 AM"],
        ["15:00", "3:00 PM"],
        ["abc", null] ];

    var testResults;
    testResults = "<table><tr><th>Input</th><th>Expected</th><th>Actual</th></tr>";

    for (var i = 0; i < testStrings.length; i++){
        testResults +=
            "<tr>" +
                "<td>" + testStrings[i][0] + "</td>" +
                "<td>" + testStrings[i][1] + "</td>" +
                "<td>" + parseTime( testStrings[i][0] ) + "</td>" +
                "<td>" + ( testStrings[i][1] == parseTime( testStrings[i][0] ) ?
                            "<span style='color:green'>Success</span>" :
                            "<span style='color:red'>Failure</span>" ) +
                "</td>" +
            "</tr>";
    }

    testResults += "</table>";

    this.document.getElementById("results").innerHTML = testResults;
}
        </script>
    </head>
    <body onload="unitTest();">

        <div id="results">
        </div>

    </body>
</html>

Output: 输出:

Input Expected Actual 输入预期实际值
1:30 PM 1:30 PM 1:30 PM Success 下午1:30 PM 1:30 PM 1:30 PM成功
1.30p 1:30 PM 1:30 PM Success 1.30p 1:30 PM 1:30 PM成功
1;30a 1:30 AM 1:30 AM Success 1; 30a 1:30 AM 1:30 AM成功
59:99 PM null null Success 59:99 PM null null成功
0,30 12:30 AM 12:30 AM Success 0:30 12:30 AM 12:30 AM成功
15:00 3:00 PM 3:00 PM Success 15:00 3:00 PM 3:00 PM成功
abc null null Success abc null null成功

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM