Tuesday, September 1, 2009

Number Only in text fields

Using javascript you can set fields to accept certain characters only using Regex strings. In the following I put the "_decimalonly" class to my text inputs, and with JQuery, when the page is loaded, all the inputs with the "_decimalonly" have the validations implemented.


Here are a few I use for inputs:


Variables for on keypress validation
var decimal = new RegExp("[-|0-9|\.]+");//decimal
var monetary = new RegExp("[0-9|\.]+");//monetary

var integer = new RegExp("[0-9]+");//positive integer
var neginteger= new RegExp("[-|0-9]+");//negative integer

Variables for on blur (submit also) validation
var decimalb = new RegExp("^-?[0-9]*\.?[0-9]{1,}?$");//decimal
var monetaryb = new RegExp("^[0-9]*\.?[0-9]{1,}?$");//monetary
var integerb = new RegExp("^[0-9]*$");//integer
var negintegerb = new RegExp("^-?[0-9]*$");//negative integer

Examples:

Example of on blur:

$("input._decimalonly").blur(function(){
var number = $(this).val();
var re = new RegExp("^-?[0-9]*\.?[0-9]{1,}?$");//monetary

if(re.test(number))
{
//its a valid number
}
else
{
$(this).val("");
}
});

Example of on keypress:

$("input._decimalonly").keypress(function(e){

if(e.which == 8) //for the backspace :)
{
return true;
}
var number = String.fromCharCode(e.which);

//var re = new RegExp("[-|0-9|\.]+");//decimal
var re = new RegExp("[0-9|\.]+");//monetary
if(re.test(number))
{
return true;
}
else
{
return false;
}
});

No comments:

Post a Comment