开发者

restrict textbox to allow only integers in asp.net through javascript

I have asp:textbox I want to res开发者_JS百科trict the text box to allow only integer values. How can I do that using javascript in asp.net.


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.


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


Check this example.

Restrict Characters and Allow only Integers in Textbox using JavaScript


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜