Arpan
Arpan

Reputation:

restrict a character to type in a text box

how we can restrict a character to type in a text box.

Upvotes: 15

Views: 60118

Answers (5)

JW P
JW P

Reputation: 193

Ben Rowe's answer is indeed the way to approach it. However, the character will appear in the textbox before it is being removed. You can prevent that by using oninput instead of onkeyup:

<input type="text" oninput="this.value = this.value.replace(/[^a-z]/, '')" />

Upvotes: 5

Jochem Schulenklopper
Jochem Schulenklopper

Reputation: 6934

Although still possible, with HTML5 there's no real need to use a JavaScript-based solution for this requirement.

<input type="text" name="text" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$"> will restrict the allowed characters according that RegExp pattern (in this case: valid-looking email addresses).

The title attribute will be used as a warning / notification when the user tries to submit the data not matching the requirement.

<form action="/add_country.php">
  Country code: <input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
  <input type="submit">
</form>

See the documentation on HTML input element for more information. Not all browsers support it equally well (like Safari) though.

Upvotes: 11

Raman Singh
Raman Singh

Reputation: 161

   function isNumberKey1(evt)
{
       var charCode = (evt.which) ? evt.which : event.keyCode;
      if ( char!=8(charCode < 65 || charCode > 106))
         return false;

         return true;
}

Upvotes: -1

Ben Rowe
Ben Rowe

Reputation: 28721

You can do this via javascript (so if javascript is off, you won't be able to restrict it)

<input type="text" onkeyup="this.value = this.value.replace(/[^a-z]/, '')" />

This will restrict it to only a-z characters. Checkout regular expressions to see what you can do

Upvotes: 25

Puru
Puru

Reputation: 9083

If you have the text box then you have to handle the onkeypress event

<input type='text' onkeypress='keypresshandler(event)' />

You can use the following function to restrict the users

    function keypresshandler(event)
    {
         var charCode = event.keyCode;
         //Non-numeric character range
         if (charCode > 31 && (charCode < 48 || charCode > 57))
         return false;
    }

Upvotes: 8

Related Questions