JavaScript: Allow alphanumeric , dash, underscore and space on keypress

/ / 0 Comments

JavaScript validates to allow Alphanumeric, space: Here in this article, we are going to learn how in JavaScript we can validate our textbox. To allow only alphanumeric, dash, underscore, or space to our Textbox using onkeypress event.

Validate input fields is a common task in any web development.

Here we are doing just client-side validation (js validation), but we also have to do server-side validation to make your app more secure.

Steps to Allow Alphanumeric, Space, and Dash in the textbox

  1. Add Html Markup Input field text
  2. JS code: using regex to validate an input field

Add Html Markup Input Field

Here 1st we add input field text, which we want to validate. So our markup looks like as written below:

<input id="txtUserName"  type="text" />

We have the textbox on our webpage, now with JavaScript, we are able to validate our textbox to allow only Alphanumeric ie( allow alphabet & numbers), spaces, and dash.

JS code: using regex to validate an input field

First, we create a regex pattern, while allowing alphabets, numeric dash, underscore, and space. Our regex pattern would be  /^[a-zd-_s]+$/i,

Little explanation of regex a-z allows us to enter alphabets. And d allow us to enter numeric values and same - _ allows the user to enter dash and underscore.

As we are done with our regex pattern, now let us create a JS function as Validate and trigger it on event onkeypress.

Our final JS code looks like as written below:

 function Validate(e) {
	var keyCode = e.keyCode || e.which;
	var errorMsg = document.getElementById("lblErrorMsg");
	errorMsg.innerHTML = "";

	//Regex to allow only Alphabets Numbers Dash Underscore and Space
	var pattern = /^[a-zd-_s]+$/i;

	//Validating the textBox value against our regex pattern.
	var isValid = pattern.test(String.fromCharCode(keyCode));
	if (!isValid) {
		errorMsg.innerHTML = "Invalid Attempt, only alphanumeric, dash , underscore and space are allowed.";
	}

	return isValid;
}

View Demo


As we have done with our JavaScript function which restricts the user to enter only alphabets, numbers, underscore, dash and space. Now we call this function on our input textbox.

Our final code looks like as written below:

<input onkeypress="return Validate(event);" type="text" />

Conclusion: Using the regex pattern we were able to validate our textbox by allowing the user to enter only Alphanumeric, and space. 

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

0 Comments