简体   繁体   中英

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
My JavaScript code is :

<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:

<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. What am I doing wrong?

This regex coupled with javascript's replace will replace only the first instance of the invalid character. Try adding g option at the end of the Regex string /[^a-zA-Z\\s]/g

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM