2

I have asp:textbox I want to restrict the text box to allow only integer values. How can I do that using javascript in asp.net.

4 Answers 4

2

If you use the replace function and some regualar expressions you will be able to do this.

<input type="text" name="textbox" onkeyup="integersOnly(this)">

<script type="text/javascript">
    function integersOnly(obj) {
        obj.value = obj.value.replace(/[^0-9-.]/g,'');
    }
</script>

That will also keep in the decimal place.

If you just want integers use:

obj.value = obj.value.replace(/[^0-9]/g,'');

All this function is doing is taking what is input and removing any characters that are not numbers.

Alternatively you can do this in jQuery. If you use jQuery let me know and I will let you know how I do it.

EDIT

Following on from your comment you could use the following updated function:

var integer_only_warned = false;
function integersOnly(obj) {
    var value_entered = obj.value;
    if (!integer_only_warned) {
        if (value_entered.indexOf(".") > -1) {
            alert('Please enter an integer only. No decimal places.');
            integer_only_warned = true;
            obj.value = value_entered.replace(/[^0-9]/g,'');
        }
    }
    obj.value = value_entered.replace(/[^0-9]/g,'');        
}

What this is doing is first checking if a decimal has been entered. If it has then it is warning the user and then removing the decimal place. I have also added a check, so that the warning only comes up once every page load.

Hope that helps.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi instead of replace Can I find whether it is integer or float(like 10.2) . If use function as u suggested its replacinng the num as 102. but can I find the number is interger or float, if float I can show alert message like enter only integer.
I have updated the answer above with an updated version of the function. Hope that helps.
2

Use a RegularExpressionValidator control and set the EnableClientScript property to True.

Comments

0

Check this example.

Restrict Characters and Allow only Integers in Textbox using JavaScript

Comments

0

Just to throw this in too, if you happen to be using AJAX Control Toolkit, there is an extender already built that makes filtering content a snap: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/FilteredTextBox/FilteredTextBox.aspx

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.