You can use either an ASP.Net validation control or manually create the validation in JavaScript.
Using an ASP.Net Validation Control:
<asp:RegularExpressionValidator runat="server"
id="DecimalTextBoxValidator"
ControlToValidate="DecimalTextBoxID"
ValidationExpression="/^[\d]{1,11}(.[\d]{1,2})?$/"
ErrorMessage="Number format is invalid."
EnableClientScript="True" />
The trick to get it to run on the client instead of the server is the
EnableClientScript="True"
attribute.
For pure JavaScript approaches:
var decimal_regex = /^[\d]{1,11}(.[\d]{1,2})?$/;
function validateDecimal(inputElement){
return decimal_regex.test(inputElement.value);
}
if(validateDecimal(submittedForm['DecimalTextBoxID'])){
}
Or, my personal favorite, add a function to the String prototype and use that in your form validating script:
if(!String.prototype.isDecimal){
String.prototype.isDecimal = function(digits, decimals){
if(digits == undefined){ digits = ""; }
if(decimals == undefined){ decimals = ""; }
var regex = new RegExp("^[\\d]{1,"+digits+"}(.[\\d]{1,"+decimals+"})?$");
return regex.test(this);
}
}
if(!submittedForm['DecimalTextBoxID'].value.isDecimal(11,2)){
}
I would avoid trying to filter input on the text box with javascript (that's a trick and half without a 3rd party library). I would also not do an onBlur/.focus() trap on the box as that tends to frustrate users more than anything else.