[code]
<html>
<head><title>用正则表达式控制输入格式</title></head>
<body>
<form>
<table border="1">
<tr>
<td>只能输入中文:</td>
<td>
<input type="text" name="mark" onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))" />
</td>
</tr>
<tr>
<td>只能输入数字:</td>
<td>
<input type="text" name="number" onkeyup="value=value.replace(/[^\d]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))" />
</td>
</tr>
<tr>
<td>只能输入数字和英文:</td>
<td>
<input type="text" name="alpha" onkeyup="value=value.replace(/[\W]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))" />
</td>
</tr>
<tr>
<td>只能输入数字和英文还有中文:</td>
<td>
<input type="text" name="chinese" onkeyup="value=value.replace(/[^\u4E00-\u9FA5^a-z^A-Z^0-9]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5^a-z^A-Z^0-9]/g,''))" />
</td>
</tr>
<tr><td colspan="2"><input type="submit"/></td></tr>
</table>
</form>
</body>
</html>[/code]
<html>
<head><title>用正则表达式控制输入格式</title></head>
<body>
<form>
<table border="1">
<tr>
<td>只能输入中文:</td>
<td>
<input type="text" name="mark" onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))" />
</td>
</tr>
<tr>
<td>只能输入数字:</td>
<td>
<input type="text" name="number" onkeyup="value=value.replace(/[^\d]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))" />
</td>
</tr>
<tr>
<td>只能输入数字和英文:</td>
<td>
<input type="text" name="alpha" onkeyup="value=value.replace(/[\W]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))" />
</td>
</tr>
<tr>
<td>只能输入数字和英文还有中文:</td>
<td>
<input type="text" name="chinese" onkeyup="value=value.replace(/[^\u4E00-\u9FA5^a-z^A-Z^0-9]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5^a-z^A-Z^0-9]/g,''))" />
</td>
</tr>
<tr><td colspan="2"><input type="submit"/></td></tr>
</table>
</form>
</body>
</html>[/code]
本文提供了一个使用HTML和JavaScript结合正则表达式的示例,演示如何限制文本框内的输入内容仅为中国汉字、数字、英文字母及这些组合。通过对输入事件的监听和处理,确保用户只能输入符合规定的字符。
656

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



