How to block special characters in a TextBox?


Looking for script to restrict special characters in a text box? We do require restricting the users from entering special characters in some text boxes in our application. This aarticle will prove you the java script and code for blocking special characters in a text box.

Sometimes we want to restrict the users of our application from entering special characters in some of the textboxes in the application.

I am providing you with the script and code to check that numbers and special characters are not inserted into a Textbox. If we enter special characters, this example will show a MessageBox saying that "Special characters are not allowed".

In this example the form displayed requires the Username textbox to accept only characters, numeric values or spaces before its content are dispatched to a Web server for further processing.

JavaScript for blocking special characters in a textbox


The Javascript for restricting/blocking special characters in the textbox is as follows:

function validateTest(objFrm)
{
//regex variable
var regex = /^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/ ;
if(objFrm.txtUsername.value=="")
//checking whether the textbox txtUsername is empty or not
{
alert("Username cannot be left blank");
//An alert box is popped up in the browser if it is with a message in it
objFrm.txtUsername.focus();
//Once the user responds to the alert the cursor is
//placed in the textbox again
return false;
//The value false is returned to the function so that
//form submission
}
else if(!regex.test(objFrm.txtUsername.value))
{
alert("Username can have alphabets, numbers and spaces.
Please provide valid Username");
// An alert box is popped up in the browser if it is
//with a message in it
objFrm.txtUsername.focus();
//Once the user responds to the alert the cursor is
//placed in the textbox again
return false;
//The value false is returned to the function so that
//form submission
}
else
{
return true;
}
}


Html code for blocking special characters in a textbox


The HTML PART of the application will be like:

<form name="frmTest" id="frmTest" method="post" >
Username <input type="text" name="txtUsername" id="txtUsername"
value="" title="Username" />
<input type="button" name="btnSubmit" id="btnSubmit"
value="Submit" onclick="return validateTest(document.frmTest);" />
<input type="reset" name="btnCancel" id="btnCancel"
value="Cancel" />

</form>


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: