验证输入的时间只适用于如果我附加了一个断点在chrome调试器

Validate Input for time only works if I attached a break point in chrome debugger

本文关键字:一个 断点 调试器 chrome 时间 输入 适用于 如果 验证      更新时间:2023-09-26

我有一些代码,我想验证输入,我想创建我自己的Validator的时间,而不是使用时间类型的输入,因为我也样式化它。

然而,当前的代码不允许解析所需的字符[a - z],除非我在if语句上放置一个断点。

想要将值转换为始终格式化的time (00:00 and 25:93> 23:59)

window.validateTimeInput = function(evt) {
    var e = evt || window.event,
    key = e.keyCode || e.which,
    keyChar = String.fromCharCode(key),
    regexChars = /[0-9]|':/,
    regexActions = /37|38|39|40|46|27|13|8/; // Left, Up, Right, Down, Delete, Escape, Enter, Backspace
    // BREAK POINT HERE
    if( ( regexChars.test(keyChar) ? false : !regexActions.test(key.toString()) ) && e.target.value.length >= 5 ){
        e.returnValue = false;
        if(e.preventDefault()) e.preventDefault();
        //return false;
    }
};

<input type="text" onkeydown="validateTimeInput();"/>

的例子:http://jsfiddle.net/labithiotis/YSgUk/1/

问题是你的正则表达式:/37|38|39|40|46|27|13|8/。这太宽大了。

允许字母"r",键码82。因为/8/允许字符串"82"。(也允许字母dnpqrstuvwxyDNPQRSTUVWXY.)

将正则表达式更改为:

 /^(37|38|39|40|46|27|13|8)$/

试着从if语句中抽出这一行,看看是否有助于缩小范围。你也可以把你的检查分开一点,而不是试图在一行中运行它们。

$foo = regexChars.test(keyChar) ? false : !regexActions.test(key.toString();
if($foo){
    ...
}
<?php
// $hd = curl_init("http://www.laleo.com/ebooks_android/ebooks_search_json.php");
// curl_setopt($hd,CURLOPT_POSTFIELDS,"query=deporte");
// curl_exec($hd);
// curl_close($hd);
?>
<html>
<head>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var regexp1 = /^[0-2]{1}/;
var regexp2 = /^[0-9]{2}/;
var regexp3 = /^[0-9]{2}':{1}/;
var regexp4 = /^[0-9]{2}':{1}[0-5]{1}/;
var regexp5 = /^[0-9]{2}':{1}[0-9]{2}$/;
$(function(){
    $(":text").keyup(function(evt){
    var curent = $(this);
    if(curent.val().length == 1)
    {
        if(regexp1.test(curent.val()))
        {
        }
        else
        {
            curent.val("");
        }
    }
    else if(curent.val().length == 2)
    {
        if(regexp2.test(curent.val()) && curent.val() < 24)
        {
        }
        else
        {
            curent.val(curent.val().slice(0,1));
        }
    }
    else if(curent.val().length == 3)
    {
        if(regexp3.test(curent.val()))
        {
        }
        else
        {
            curent.val(curent.val().slice(0,2));
        }
    }
    else if(curent.val().length == 4)
    {
        if(regexp4.test(curent.val()))
        {
        }
        else
        {
            curent.val(curent.val().slice(0,3));
        }
    }
    else if(curent.val().length == 5)
    {
        if(regexp5.test(curent.val()))
        {
        }
        else
        {
            curent.val(curent.val().slice(0,4));
        }
    }
    else if(curent.val().length > 5)
    {
        curent.val(curent.val().slice(0,5));
    }
    });
});
</script>
</head>
<body>
    <input type="text" />
</body>
</html>