十进制格式的用户输入时间。
喜欢
//Incorrect
//Correct value
//Incorrect value
//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;
答案 0 :(得分:1)
使用数字可能更容易:
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' );