Thursday, June 14, 2012

JavaScript - input validators alphanumeric

Here's a simple way to validate user input on fly, one is letters only + spacebar, the other one is numbers only


<input type="text" id="tb_name" onkeypress="return filter_alpha(this)"></td>

<input type="text" id="tb_number" onkeypress="return filter_numeric(this)"></td>


function filter_alpha(input_txt) {
      input_txt = (input_txt) ? input_txt : event;
      var charCode = (input_txt.which) ? input_txt.which : event.keyCode
    if (charCode > 32 && (charCode < 65 || charCode > 90) &&
       (charCode < 97 || charCode > 122)) {
       return false;
    }
    return true;
}

function filter_numeric(input_txt) {
    var charCode = (input_txt.which) ? input_txt.which : event.keyCode
            if (charCode != 46 && charCode > 31
              && (charCode < 48 || charCode > 57))
               return false;

            return true;
}

Cheers!

No comments:

Post a Comment