<%@ 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 pressFloat(e, intType) {
var value = String.fromCharCode(e.keyCode);
if ("1" == intType) {
if ( (value >= "0" && value <= "9") || value == "." ) {
return true;
} else {
return false;
}
} else {
if ((value >= "0" && value <= "9") || value == "-" || value == "." ) {
return true;
} else {
return false;
}
}
}
/*
校验输入域可以录入正数(正、负、所有),一般与pressInt事件一同使用
@ param : field input域
@ param : intType 整数类型,正、负,或者所有(1,只校验正数,-1,只校验负数,其它校验所有)
*/
function checkFloat(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 = /(^[0][.]\d*[1-9]+$)/;
//以非0开头的浮点数
var reg2 = /(^[1-9]+\d*[.]\d*[1-9]+$)/;
var reg11 = /(^[-][0][.]\d*[1-9]+$)/;
//以非0开头的浮点数
var reg21 = /(^[-][1-9]+\d*[.]\d*[1-9]+$)/;
//负数的校验:以-开头,非0其后
if ("1" == intType) {//校验正数
//浮点数,无论正负,一个以0.开头,另外其它
if (reg1.test(value) || reg2.test(value) ) {//在校验范围之内
} else {
alert("Sys:\r所录入的值非正浮点数");
field.select();
field.focus();
}
} else if ("-1" == intType) {//校验负数
if (reg11.test(value) || reg21.test(value)) {//在校验范围之内
} else {
alert("Sys:\r所录入的值非负浮点数");
field.select();
field.focus();
}
} else {
if (reg1.test(value) || reg2.test(value) || reg11.test(value) || reg21.test(value)) {//在校验范围之内
} else {
alert("Sys:\r所录入的值非浮点数");
field.select();
field.focus();
}
}
}
}
</script>
</head>
<body>
<input name="test" οnkeypress="return pressFloat(event)"
οnblur="checkFloat(this)" />
</body>
</html>
Js控制录入域为浮点数
最新推荐文章于 2022-05-13 06:59:57 发布