input輸入框中輸入格式的限定
阿新 • • 發佈:2018-12-26
一般是根據正則表示式匹配的:下面是幾個正則表示式的含義
- /i (忽略大小寫)
- /g (全文查找出現的所有匹配字元)
- /m (多行查詢)
- /gi(全文查詢、忽略大小寫)
- /ig(全文查詢、忽略大小寫)
0.文字框不能黏貼文字
<input onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))">
onbeforepaste 意思是在使用者執行貼上動作之前。
clipboardData.setData('text', xxx) 是把xxx的內容複製到剪貼簿
clipboardData.getData('text') 是讀出當前剪貼簿裡的內容,
.replace(/[^\d]/g,'') 是正則替換,把裡面除了數字以外的字元全部都去掉,
整個語句的功能是,每當使用者執行貼上操作前,先取出剪貼簿的內容字串,刪除不是數字的字元,只保留數字,然後再貼上,而不是直接貼上
1.文字框只能輸入數字程式碼(小數點也不能輸入)
<input onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')">
2.只能輸入數字,能輸小數點.
<input
onkeyup="if(isNaN(value))execCommand('undo')"
onafterpaste="if(isNaN(value))execCommand('undo')">
<input
name=txt1
onchange="if(/\D/.test(this.value)){alert('只能輸入數字');this.value='';}">
3.只能輸入字母和漢字
<input onkeyup="value=value.replace(/[\d]/g,'') " onbeforepaste ="clipboardData.setData('text',clipboardData.getData('text').replace(/[\d]/g,''))" maxlength=10 name="Numbers">
4.只能輸入英文字母和數字,不能輸入中文
<input onkeyup="value=value.replace(/[^\w\.\/]/ig,'')">
5.只能輸入數字和英文
<input onKeyUp="value=value.replace(/[^\d|chun]/g,'')">
6.小數點後只能有最多兩位(數字,中文都可輸入),不能輸入字母和運算子號:
<input onKeyPress="if((event.keyCode<48 || event.keyCode>57) && event.keyCode!=46 || /\.\d\d$/.test(value))event.returnValue=false">
7.小數點後只能有最多兩位(數字,字母,中文都可輸入),可以輸入運算子號:
<input onkeyup="this.value=this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')">
8.用JS的正則表示式如何判斷輸入框內為中文或者是英文數字,或者是三者混編:
- 只能輸入數字和英文的:
<input onkeyup="value=value.replace(/[\W]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))">
- 只能輸入數字的:
<input onkeyup="value=value.replace(/[^\d]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))">
- 只能輸入全形的:
<input onkeyup="value=value.replace(/[^\uFF00-\uFFFF]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\uFF00-\uFFFF]/g,''))">
- 只能輸入漢字的:
<input onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))">
也可以這樣:
<input type=text name= caolig value ="" onblur="if (!(/^[\d]+\.?\d*$/.test(this.value)) ){alert('您的輸入有誤'); this.value='';this.focus();}">