用户以十进制格式输入时间。
喜欢
- 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/