开发者

restrict a character to type in a text box

how we can restrict a character to type in a text开发者_高级运维 box.


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


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.


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;
    }


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]/, '')" />


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

         return true;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜