In this article I will explain with an example, how to allow only
AlphaNumeric (Letters or Numbers),
Underscore in
Username and it must have length of 3 to 10 characters 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 HTML Markup consists of an
HTML TextBox, SPAN element and a Button.
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 and Underscore in Username and must contain 3 to 10 characters
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_]{3,10}$/;
if (!expr.test(username)) {
lblError.innerHTML = "Only Alphabets, Numbers and Underscore and between 3 to 10 characters.";
}
}
</script>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads