In this article I will explain with an example, how to allow only AlphaNumeric, Dot (Period) and Underscore characters in Username using JavaScript.
When the Submit Button is clicked, the Username in the TextBox will be validated using JavaScript and Regular Expression (Regex) and if the Username is invalid, the error message will be displayed next to the TextBox using JavaScript.
 
 
HTML Markup
The following HTML Markup consists of an HTML TextBox, SPAN element and a Button. The Button has been assigned an OnClick event handler which calls the ValidateUsername JavaScript function.
<input type="text" id="txtUsername" />
<br />
<span id="lblError" style="color: red"></span>
<br />
<br />
<input type="button" id="btnValidate" value="Submit" onclick="ValidateUsername()" />
 
 
JavaScript function to allow only AlphaNumeric, Dot (Period) and Underscore in Username
When the Submit Button is clicked, the Username in the TextBox will be validated using JavaScript and Regular Expression (Regex) and if the Username is invalid, the error message will be displayed next to the TextBox using JavaScript.
<script type="text/javascript">
    function ValidateUsername() {
        var username = document.getElementById("txtUsername").value;
        var lblError = document.getElementById("lblError");
        lblError.innerHTML = "";
        var expr = /^[a-zA-Z0-9._]*$/;
        if (!expr.test(username)) {
            lblError.innerHTML = "Only Alphabets, Numbers, Dot and Underscore allowed in Username.";
        }
    }
</script>
 
 
Screenshot
Allow only AlphaNumeric, Dot (Period) and Underscore in Username 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