javascript - 如何使用 javascript 验证十进制时间?

标签 javascript jquery regex

用户以十进制格式输入时间。

喜欢

  • 0.00 //不正确
  • 1.54 //正确值
  • 1.60 //值不正确
  • 1.59 //正确值

我尝试创建一个正则表达式函数,但所有值都显示不正确

var regex = /^[0-9]\d*(((,?:[1-5]\d{3}){1})?(\.?:[0-9]\d{0,2})?)$/;
 if (args.Value != null || args.Value != "") {
    if (regex.test(args.Value)) {
        //Input is valid, check the number of decimal places
        var twoDecimalPlaces = /\.\?:[1-5]\d{2}$/g;
        var oneDecimalPlace = /\.\?:[0-9]\d{1}$/g;
        var noDecimalPlacesWithDecimal = /\.\d{0}$/g;

        if (args.Value.match(twoDecimalPlaces)) {

            //all good, return as is
            args.IsValid = true;
            return;
        }
        if (args.Value.match(noDecimalPlacesWithDecimal)) {
            //add two decimal places
            args.Value = args.Value + '00';
            args.IsValid = true;
            return;
        }
        if (args.Value.match(oneDecimalPlace)) {
            //ad one decimal place
            args.Value = args.Value + '0';
            args.IsValid = true;
            return;
        }
        //else there is no decimal places and no decimal
        args.Value = args.Value + ".00";
        args.IsValid = true;
        return;
    } else
        args.IsValid = false;
} else
    args.IsValid = false;

最佳答案

使用数字可能更容易:

var time = (+args.Value).toFixed(2); // convert to float with 2 decimal places
if (time === args.Value) {
    // it's a valid number format
    if (time !== 0.0 && time < 24) {
        // the hours are valid
        if (time % 1 < 0.6) {
            // the minutes are valid
        }
    }
}

您可以将所有内容折叠成一行漂亮的文字:

if (time === args.Value && time !== 0.0 && time < 24 && time % 1 < 0.6) {
}

甚至是 bool 值/三元值

var valid = time === args.Value && time !== 0.0 && time < 24 && time % 1 < 0.6;
alert( time === args.Value && time !== 0.0 && time < 24 && time % 1 < 0.6 ? 'valid' : 'invalid' );

关于javascript - 如何使用 javascript 验证十进制时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25998790/

相关文章:

javascript - 如何检查 DOM 节点是否为 `html` 节点

javascript - 在应用程序数据中存储和检索 WinJS.Binding.List

jQuery 1.8.1 .load html>body

javascript - jquery 输入文本与替换不起​​作用

regex - a{0,1}|b{0,1} 只匹配 'a' ,为什么?

javascript - jQuery 动态排序 AppendTo

javascript - 复制到 Dreamweaver 时 JSFiddle 字符计数不起作用

java - 使用 Java 模式的字符串定界符

regex - 如何使用 RegEx 禁止 ColdFusion 中的非字母数字字符

javascript - 从数组中查找对象的值