Restrict users from entering special characters and numbers

How can I restrict users from entering special characters and numbers in the text box. I want only alphabets to be entered ( Typed / Pasted ).

give me sample javascript codes?


Rather than preventing the entry of certain characers, it is far more user friendly and effective to validate the value when the form is submitted. You really don't care what the value of the field is before that, and you don't need special handling for how the value is entered. It might be pasted, dragged, auto-entered, entered by a plugin or script, or other methods.

A trivial example:


<form onsubmit="return validate(this);">
  <input type="text" name="foo">
  <input type="submit">

<script type="text/javascript">
function validate(form) {
  var re = /^[a-z,A-Z]+$/i;

  if (!re.test( {
    alert('Please enter only letters from a to z');
    return false;

Take a look at this question: Function to return only alpha-numeric characters from string?

This is what you're after:

$result = preg_replace("/[^a-zA-Z0-9]+/", "", $inputVar);

If you're inserting that into the database after that, be sure to use something like mysql_real_escape_string() or prepared statements.

Relying on Javascript solely for character validation is a very bad practice since JS can easily be disabled, and is not enabled on all devices globally.

You can try this, I'm using this right now for my current project


/* Allow integers only in form input field with id #selector */
$('#selector').keyup(function () { 
    this.value = this.value.replace(/[^0-9\.]/g,'');

It also doesn't allow the copy paste, but the weakness is the right click then paste

Disclaimer: I just found it from the internet

Need Your Help

Morphing Critter in GridWorld?

java debugging gridworld

For this new critter called AntCritter, I overwrote the processActors method and now it removes the other antcritters around it when it's supposed to change their and its color. I've tried a whole ...

Using kinect to track a hand without a body image


I'm just learning to develop on Kinect. I know that its algorithm uses a probability distribution on individual pixels to decide on the body part in the region.