In this article I will explain with an example, how to check if String contains only Alphabets (Letters) and Numbers (Digits) using JavaScript.
This article will illustrate how to use Regular Expression which allows Alphabets (Letters) and Numbers (Digits) i.e. AlphaNumeric characters to filter out all unwanted characters using JavaScript.
 
 
HTML Markup
The following HTML Markup consists of an HTML TextBox and a Button.
Name: <input type="text" id="txtName"/>
<br/>
<br/>
<input type="button" value="Submit" onclick="Validate()"/>
 
 
Check if String contains only Alphabets (Letters) and Numbers (Digits) using Regular Expression in JavaScript
When the Button is clicked, the Validate JavaScript function is called. Inside the Validate JavaScript function, the value of the TextBox is tested against the Regular Expression Alphabets (Letters) and Numbers (Digits) i.e. AlphaNumeric.
Thus if the String i.e. the TextBox value consists of any character other than Alphabets (Letters) and Numbers (Digits) then it will be considered invalid and the result will be displayed in JavaScript Alert Message Box.
<script type="text/javascript">
    function Validate() {
        //Regex for Valid Characters i.e. Alphabets and Numbers.
        var regex = /^[A-Za-z0-9]+$/
 
        //Validate TextBox value against the Regex.
        var isValid = regex.test(document.getElementById("txtName").value);
        if (!isValid) {
            alert("Only Alphabets and Numbers allowed.");
        }
 
        return isValid;
    }
</script>
 
 
Screenshot
Check if String contains only Alphabets (Letters) and Numbers (Digits) using JavaScript
 
 
Browser Compatibility

The above code has been tested in the following browsers.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Demo
 
 
Downloads