JS控制文本框只能输入正整数和两位小数点以内的小数
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>无标题页</title>
<script type="text/javascript" language="javascript">
function regInput(obj, reg, inputStr)
{
var docSel = document.selection.createRange()
if (docSel.parentElement().tagName != "INPUT") return false
oSel = docSel.duplicate()
oSel.text = ""
var srcRange = obj.createTextRange()
oSel.setEndPoint("StartToStart", srcRange)
var str = oSel.text + inputStr + srcRange.text.substr(oSel.text.length)
return reg.test(str)
}
</script>
</head>
<body>
<form id="form1" runat="server">
测试服务器控件:
<asp:TextBox ID="txt1" runat="server" onkeypress="return regInput(this,/^\d*\.?\d{0,2}$/,String.fromCharCode(event.keyCode))"
onpaste="return regInput(this,/^\d*\.?\d{0,2}$/,window.clipboardData.getData('Text'))"
ondrop="return regInput(this,/^\d*\.?\d{0,2}$/,event.dataTransfer.getData('Text'))"
Style="ime-mode: Disabled"></asp:TextBox><br />
测试html控件:
<input onkeypress="return regInput(this,/^\d*\.?\d{0,2}$/,String.fromCharCode(event.keyCode))"
onpaste="return regInput(this,/^\d*\.?\d{0,2}$/,window.clipboardData.getData('Text'))"
ondrop="return regInput(this,/^\d*\.?\d{0,2}$/,event.dataTransfer.getData('Text'))"
style="ime-mode: Disabled">
</form>
</body>
</html>