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

How to Validate Time in decimal using javascript?

本文关键字:十进制 时间 验证 javascript 何使用      更新时间:2023-09-26

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

  • 0.00 //Incorrect
  • 1.54 //Correct value
  • 1.60 //Incorrect value
  • 1.59 //correct value

我试图制作一个正则表达式函数,但它对所有值都显示不正确

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) {
}

甚至是布尔值/三值

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' );