Share this page 

Restrict input to alphanumeric and uppercaseTag(s): Form Form


The first method should work in all browsers but does not prevent pasting from the mouse (onblur will work though). The second method works in a satisfactory way in IE6.
Method 1<input type="text"
       onkeydown="f(this)"
       onkeyup="f(this)"
       onblur="f(this)"
       onclick="f(this)" />

Method 2<input type="text"
       onattrmodified="g(this)"
       onpropertychange="g(this)" />

<script type="text/javascript">
function f(o){
  o.value=o.value.toUpperCase().replace(/([^0-9A-Z])/g,"");
}

function g(o){
  if(/[^0-9A-Z]/.test(o.value)){
    o.value=o.value.toUpperCase().replace(/([^0-9A-Z])/g,"");
  }
}
</SCRIPT>
Try it here

Method 1 Method 2


If you need only to restrict to uppercase then you can apply a specific style, no javascript is needed.

Thanks to RW Anderson for the tip!

<input type="text" style="text-transform: uppercase;" />

Try it here :

An interesting effect is to restrict to lowercase and use a "small caps" font.

<input type="text" style="text-transform: lowercase;font-variant: small-caps;" />

Try it here :