验证input表单元素中的值,限定为1 ~ 100之间,精确到0.1。如果输入不合法,弹出提示信息。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>输入验证</title>
<style type="text/css">
.outer_big_box {
padding-left: 200px;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
}
input[type="number"]{
-moz-appearance: textfield;
padding-left: 8px;
}
.input_wrap {
position: relative;
}
.input_validation_tip_box {
border: 1px solid red;
display: none;
padding: 5px 15px;
position: absolute;
left: -30%;
top: 130%;
}
.input_validation_tip_box .arrow {
width: 10px;
height: 10px;
border-left: 1px solid red;
border-top: 1px solid red;
position: absolute;
top: -6px;
left: 50%;
background-color: #fff;
transform: rotate(45deg);
}
.hide_tip_box {
display: none;
}
.show_tip_box {
display: block;
}
</style>
</head>
<body>
<div class="outer_big_box">
<div class="input_wrap">
<input type="number" class="number_validation"/>
<div class="input_validation_tip_box">
<span class="arrow"></span>
<span>请输入0~100之间的值</span>
</div>
</div>
</div>
</body>
<script type="text/javascript" src="jquery-1.11.1.js"></script>
<script type="text/javascript">
$(function(){
$('.input_wrap').on('input', '.number_validation',function(){
var $this = $(this);
var val = $this.val();
var reg = /^((\d{1,2})(\.\d+)?|(0+(\d{1,2})(\.)?\d+)|(0+100(\.)0+)|100|100(\.[0]+))$/;
// var flag = (0 <= val && val <= 100) ? true : false;
// if (!flag) {
if (!reg.test(val)) {
// 显示
$('.input_validation_tip_box').removeClass('hide_tip_box');
$('.input_validation_tip_box').addClass('show_tip_box');
}else {
// 隐藏
$('.input_validation_tip_box').removeClass('show_tip_box');
$('.input_validation_tip_box').addClass('hide_tip_box');
}
if (val == '') {
$('.input_validation_tip_box').removeClass('show_tip_box');
$('.input_validation_tip_box').addClass('hide_tip_box');
}
});
});
</script>
</html>