jquery仅验证5-60之间的数字

时间:2016-10-07 07:29:41

标签: javascript php jquery arrays validation

我正在尝试验证5-60之间的数字

<div class="col-md-3">
    <input type="text" name="gd_time" id="gd_time" placeholder="Should b/w 5 to 60 " class="form-control">
</div>

我试过这个脚本但没有工作:

//gd time
var gd_time = $("#gd_time").val();
var gdtimereg = [1-9]\d*|0\d+;
if((gd_time == '') || (!gdtimereg.test(gd_time))) 
{
    $("#gd_time").css({"border-style": "solid", "border-color": "red" });
    $("#showMessage").html('Please enter the gd time should be 5 to 60 minutes');
    $("#gd_time").focus();
    return false;
} 
else{
    $("#gd_time").css({"border-style": "solid","border-color": "#E9E9E9"});
}

1 个答案:

答案 0 :(得分:1)

将值转换为Number并使用if语句对其进行验证。

检查以下示例。

&#13;
&#13;
//gd time
var gd_time = new Number($("#gd_time").val());

if (gd_time >= 5 && gd_time <= 60) {
  $("#gd_time").css({
    "border-style": "solid",
    "border-color": "#E9E9E9"
  });
} else {
  $("#gd_time").css({
    "border-style": "solid",
    "border-color": "red"
  });
  $("#showMessage").html('Please enter the gd time should be 5 to 60 minutes');
  $("#gd_time").focus();
}
&#13;
input {
  outline: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="gd_time" />
&#13;
&#13;
&#13;