<script>
function regInput(reg)
{
var srcElem = event.srcElement
var oSel = document.selection.createRange()
var srcRange = srcElem.createTextRange()
oSel.setEndPoint("StartToStart", srcRange)
var num = oSel.text + String.fromCharCode(event.keyCode) + srcRange.text.substr(oSel.text.length)
event.returnValue = reg.test(num)
}
</script>
小写英文:<xmp style="display:inline"> </xmp><input id=test onkeypress="regInput(/^[a-z]*$/)" style="ime-mode:Disabled"><br>
大写英文:<xmp style="display:inline"> </xmp><input id=test onkeypress="regInput(/^[A-Z]*$/)" style="ime-mode:Disabled"><br>
任意数字:<xmp style="display:inline"> </xmp><input id=test onkeypress="regInput(/^[0-9]*$/)" style="ime-mode:Disabled"><br>
限2位小数:<xmp style="display:inline"> </xmp><input id=test onkeypress="regInput(/^/d*/.?/d{0,2}$/)" style="ime-mode:Disabled"> 如: 123.12<br>
日 期:<xmp style="display:inline"> </xmp><input id=test onkeypress="regInput(/^/d{1,4}([-//](/d{1,2}([-//](/d{1,2})?)?)?)?$/)" style="ime-mode:Disabled"> 如: 2002-9-29<br>
任意中文:<xmp style="display:inline"> </xmp><input onkeypress="regInput(/^$/)"><br>
部分英文:<xmp style="display:inline"> </xmp><input onkeypress="regInput(/^[a-e]*$/i)" style="ime-mode:Disabled"> 范围: a,b,c,d,e<br>
部分中文:<xmp style="display:inline"> </xmp>
<script language=javascript>
function checkChinese(oldLength, obj)
{
var oTR = window.document.selection.createRange()
oTR.moveStart("character", -1*(obj.value.length-oldLength))
oTR.text = oTR.text.replace(/[^一二三四五六七八九十]/g, "")
}
</script>
<input onkeypress="return false" onkeydown="setTimeout('checkChinese('+this.value.length+','+this.uniqueID+')', 1)"> 范围: 一二三四五六七八九十<br>

此博客主要展示了使用JavaScript实现输入框字符规则验证的代码。定义了regInput函数,可对小写英文、大写英文、任意数字、限2位小数、日期等不同类型输入进行规则验证。还给出了部分英文和部分中文输入的验证代码,如部分中文限定为一二三四五六七八九十。
465

被折叠的 条评论
为什么被折叠?



