JS控制录入域为整数

<%@ page language="java" contentType="text/html; charset=GB18030"
	pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
<script type="text/javascript">
	/* 去掉首尾空格字符串 */
	function trim(s) {
		if (s == null) {
			return null;
		} else {
			return s.replace(/(^\s*)|(\s*$)/g, "");
		}
	}
	/*
	 校验输入域可以录入正数(正、负、所有),一般与checkInt事件一同使用
	 @ param : e 键盘事件,event
	 @ param : intType 整数类型,正、负,或者所有(1,只可以录入正数,其它不控制正负)
	 */
	function pressInt(e, intType) {
		var value = String.fromCharCode(e.keyCode);
		if ("1" == intType) {
			if (value >= "0" && value <= "9") {
				return true;
			} else {
				return false;
			}
		} else {
			if ((value >= "0" && value <= "9") || value == "-") {
				return true;
			} else {
				return false;
			}
		}
	}
	/*
	 校验输入域可以录入正数(正、负、所有),一般与pressInt事件一同使用
	 @ param : field input域
	 @ param : intType 整数类型,正、负,或者所有(1,只校验正数,-1,只校验负数,其它校验所有)
	 */
	function checkInt(field, intType) {
		var value = field.value;
		value = trim(value);
		if (value == "" || value == null || value == "0"   ) {

		}else if( value.match(/(^[0]+$)/) ){
			field.value = "0";
		}else if(value.match(/(^[-][0]+$)/)){
			field.value = "0";
			
		} else {//若有值
			//正数的校验:以非0的正整数开头
			var reg1 = /(^[1-9]+\d*$)/;
			//负数的校验:以-开头,非0其后
			var reg2 = /(^[-][1-9]+\d*$)/;
			if ("1" == intType) {//校验正数
				if (reg1.test(value)) {//在校验范围之内
				} else {
					alert("Sys:\r所录入的值非正整数");
					field.select();
					field.focus();
				}
			} else if ("-1" == intType) {//校验负数
				if (reg2.test(value)) {//在校验范围之内
				} else {
					alert("Sys:\r所录入的值非负整数");
					field.select();
					field.focus();
				}
			} else {
				if (reg1.test(value) || reg2.test(value)) {//在校验范围之内
				} else {
					alert("Sys:\r所录入的值非整数");
					field.select();
					field.focus();
				}
			}

		}
	}
</script>
</head>
<body>
	<input name="test" οnkeypress="return pressInt(event)"
		οnblur="checkInt(this,1)" />
</body>
</html>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值