Genpact Cora Knowledge Center

Support

Add Numeric Validation to a Textbox Control

Use these markup and JavaScript code samples to add numeric validation to a Textbox control.

Markup

<sq:TextBox runat="server" ID="TextBox1"  MaxLength="15" >
   <ClientEvents OnKeyPress="IsDecimal_OnKeyPress" OnBlur="IsDecimal_OnBlur"/>
</sq:TextBox>

JavaScript

function IsDecimal_OnBlur(sender, eventArgs) {
   var c = sender.get_value();
   if(!IsNumeric(c))
   {
      alert("Your message");
      sender.set_value();
   }
}

function IsDecimal_OnKeyPress(sender, eventArgs) {
   var c = eventArgs.get_keyCode();
   if ((c < 48) || (c > 57))
   {
      eventArgs.set_cancel(true);
   }
}
 
function IsNumeric(sText) {
    var ValidChars = "0123456789";
    var IsNumber = true;
    var Char;
 
    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
 }