views:

36

answers:

1

Hi, i'm trying to validate an input field and store it using AJAX
My js 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 js regex tester and it worked. What am i doing wrong?

+1  A: 

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

Marek Karbarz
Whew! Thank you.
wretrOvian