[英]Javascript Regular Expression to remove any characters other than letters or space
I'm trying to validate an input field and store it using AJAX 我正在尝试验证输入字段并使用AJAX进行存储
My JavaScript code is : 我的JavaScript代码是:
<script type='text/javascript'>
function addICValidate() {
var invalidString=/[^a-zA-Z\s]/; // Alphabets with spaces only
var searchQuery=document.getElementById('addICName').value;
var validQuery=searchQuery.replace(invalidString,"");
document.getElementById('addICName').value=validQuery;
return true;
}
function addIC() {
if(addICValidate()) {
hideAddICBox();
var ajaxObj=newAjaxObj();
if(ajaxObj) {
ajaxObj.onreadystatechange=function() {
if(ajaxObj.readyState==4) {
hideAddICBox();
addUpdateItemForm();
}
}
var ICName=document.getElementById('addICName').value;
url="addICSubmit.php?ICName="+ICName;
url = encodeURI(url);
ajaxObj.open("GET",url,true);
ajaxObj.send(null);
}
}
return false; // Required
}
</script>
And here's the HTML: 这是HTML:
<form id='addICForm' name='addICForm' action='#' onsubmit='return addIC()'>
<table width=100% align='center' id='addICAttList'>
<tr>
<td>Name</td>
<td><input type='text' id='addICName' name='addICName' /></td>
</tr>
<tr>
<td align='right'><input type='submit' value='Add Item' /></td>
<td align='left'><input type='reset' value='Clear' /></td>
</tr>
</table>
</form>
But the replace isn't working! 但是替换无效! I tried the regex in an online JavaScript regex tester and it worked. 我在一个在线JavaScript regex测试器中尝试了regex,并且它起作用了。 What am I doing wrong? 我究竟做错了什么?
This regex coupled with javascript's replace
will replace only the first instance of the invalid character. 此正则表达式加上javascript的replace
将仅替换无效字符的第一个实例。 Try adding g
option at the end of the Regex string /[^a-zA-Z\\s]/g
尝试在正则表达式字符串/[^a-zA-Z\\s]/g
的末尾添加g
选项
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.