In this article I will explain with an example, how to check whether string contains special characters using JavaScript.
 
 

HTML Markup

The HTML Markup consists of following elements:
TextBox – For capturing user input.
Button – For validating string.
The Button has been assigned with a JavaScript onclick event handler.
Name:<input type="text" id="txtName" /> 
<br />
<br />
<input type="button" value="Submit" onclick="Validate()" />
 
 

Checking Special Characters in string using Regular Expression in JavaScript

When the Button is clicked, the Validate JavaScript function is called.
Inside this function, first the Regular Expression is defined and the value of the TextBox is tested against it.
If string i.e. TextBox value any character other than Alphabets, Numbers or Space then it will be considered as invalid and an appropriate message will be displayed in JavaScript Alert Message Box.
<script type="text/javascript">
    function Validate() {
        //Regex for Valid Charactersi.e. Alphabets, Numbers and Space.
        var regex = /^[A-Za-z0-9 ]+$/
 
        //Validate TextBox value against the Regex.
        var isValid regex.test(document.getElementById("txtName").value);
        if (!isValid) {
            alert("Contains Special Characters.");
         }else {
            alert("Does not contain Special Characters.");
        }
 
        return isValid;
    }
</script>
 
 

Screenshot

Check whether String contains Special Characters using JavaScript
 
 

Browser Compatibility

The above code has been tested in the following browsers.
Microsoft Edge   FireFox  Chrome  Safari  Opera
* All browser logos displayed above are property of their respective owners.
 
 

Demo

 
 

Downloads