How to write a javascript function to check that my text box contains a special character or not?

advertisements

I want to check that my text box is containing special character or not, using java script. for this i am using following code

function CheckUserId() {
    var txt = document.getElementById('<%=TextBox1.ClientID%>').value;
    var regexp = "/^[a-zA-Z0-9]+$/";
    if (regexp.match(txt)) {
        alert("No special character ");
        return true;
    }
    else {
        alert("Special character");
        return false;
    }
    }

I am calling this java script function on textbox onblur. TextBox code is following

  <asp:TextBox ID="TextBox1" runat="server" onblur="CheckUserId()" ></asp:TextBox>

but it is showing always alert message "special character" .Whats wrong with my code? Please help me


You have the string and the pattern the wrong way round on your if statement. The syntax for a javascript match is string.match(regexp). Try instead:

if (txt.match(regexp))