Forcing html input type entry with jQuery

You should also do both client side and server side validation, never rely on just one method. Fortunately, jQuery makes the client side super easy. I won’t discuss validation per se, instead, we’ll focus on limiting the TYPE of data that can be entered in an input field.

Just add these two simple functions to your $(document).ready section. From now, on, any html input with the associated class assigned will limit the type of data that can be entered.

$(document).ready(function() {
    // common functions using class to control input entry
    $('.only_alpha').bind('keyup blur',function(){
        $(this).val( $(this).val().replace(/[^a-zA-z]/g,'') ); }
    // Apply the class numericOnly to any html input to force it to only accept numbers
    $(".only_numeric").bind('keypress', function (e) {
        return ( e.which != 13 && e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) && e.which != 46) ? false : true;

Now, to have an input that only accepts alpha characters, you just add the class “only_alpha” to it.

<input type="text" name="name_first" class"only_alpha" />

Likewise, to limit an input to numeric characters only, just add the class “only_numeric”.

<input type="text" name="name_first" class"only_numeric" />

For true compliance, you can also use the new HTML5 types. I won’t go into these here, but you can get a nice overview at