Allowing Only Numbers in ASP. NET TextBoxes
ASP.NET validation controls provide basic web form validations. In some cases
you need more control on the validation process. CustomValidator control lets
you take charge of the validation process. You can wire up your own client side
CustomValidator control to allow only numbers in an ASP.NET textbox.
You might think - we are anyway using CustomValidator and writing a client
side function on our own then why not use your
is directly attached with an ASP.NET control through Attributes collection and
not via CustomValidator control. There are few reasons:
- You can take advantage of same programming model as of the rest of
- Your validation failure is easily displayed in ValidationSummary control
- With CustomValidator you can also get chance to write server side
How CustomValidator works?
CustomValidator control has a property called ClientValidationFunction. This
will perform the validation for you. Note that EnableClientScript property must
be true for this to work (by default it is true). The general syntax of the function is like
Here, the arguments parameter contains a property called IsValid that needs
to be set to true or false. If you set it to false then ASP.NET treats as if
validation has failed and error message is displayed accordingly.
Example - Allowing only numbers in a TextBox
Let's see how we can use CustomValidator to allow only numeric entries in a
- Create a new project in VS.NET of type - ASP.NET Web Application.
- On the web form drag and drop a TextBox, Label and a Button
- Add one RequiredFieldValidator, a CustomValidator and ValidationSummary
- Set ControlToValidate property of both the validation controls to
- Set ErrorMessage property of RequiredFieldValidator to "Field can not be
- Set ErrorMessage property of CustomValidator to "Only Numbers are
- Set ClientValidationFunction property to IsNumber. IsNumber is a
- Write following function in the <script> block:
var ValidChars = "0123456789.";
for (i = 0; i < sText.length; i++)
Char = sText.charAt(i);
if (ValidChars.indexOf(Char) == -1)
arguments.IsValid = false;
- In above function we are checking whether entered value
contains anything from 0123456789 and . (period). If you wish you could have
added more validation as per your requirements.
- You can now test the validation by entering some alphabets in the
You can download and run the complete example attached along with the
ASP.NET CustomValidator allows you take complete control of the validation
CustomValidator that takes care of your validation. In our example we provided a
function that ensures that entered value in number only.