我使用javascript函数仅清理输入数据的数字
<input type="text" onkeypress="return isNumberKey(event)">
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
但我希望允许A,B和*输入数据。该javascript代码应该怎么做?
答案 0 :(得分:0)
使用oninput
事件,即使用户进行了复制粘贴,也会触发此事件
试试这种方式
<input type="text" oninput="return isNumberKey(this)">
function isNumberKey( thisObj ){
var regex = new RegExp("[0-9]+", "g");
return regex.test( thisObj.value );
}
您可以将正则表达式扩展为输入以仅允许输入数据中的 A,B,0-9和*
var regex = new RegExp("[0-9AB*]+", "g");
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var regex = new RegExp("[0-9]+", "");
return regex.test(String.fromCharCode( charCode ) );
}
<input type="text" onkeypress="return isNumberKey( event )" oninput="return isNumberKey( event )">
答案 1 :(得分:-1)
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Regex to allow special characters, spaces and alphanumeric</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function() {
$('#btnValidate').click(function() {
var txt = $('#txtdesc').val();
var re = /^[ A-Za-z0-9_@./#&+-]*$/
if (re.test(txt)) {
alert('Valid Text')
}
else {
alert('Please Enter Valid Text');
return false;
}
})
})
</script>
</head>
<body>
<div>
Enter Text :<input type="text" id="txtdesc" />
<input type="button" id="btnValidate" value="Validate" />
</div>
</body>
</html>