1

I have a textbox where user can insert only numbers. So I tried with below link

JS FIDDLE

But still I am able to insert [.] (decimal) in the textbox. Below is what I tried

 $(".allownumericwithoutdecimal").on("keypress keyup blur",function (event) {    
       $(this).val($(this).val().replace(/[^\d].+/, ""));
        if ((event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }

Textbox

<igtxt:WebNumericEdit ID="txtNoofPages" Width="24%" runat="server" CssClass="allownumericwithoutdecimal">
            </igtxt:WebNumericEdit>
Nad
  • 4,605
  • 11
  • 71
  • 160
  • http://stackoverflow.com/questions/9204783/how-do-i-validate-a-decimal-field-with-jquery-and-regex – MusicLovingIndianGirl May 12 '16 at 05:56
  • 1
    Messing with key input is not user friendly, far better to just show an on–screen hint if the value seems invalid and let the user fix it themselves. Sniffing keys doesn't stop invalid values being pasted, or dragged and dropped into the field, Oh, and `$(this).val()` is just a very inefficient way of doing `this.value`. – RobG May 12 '16 at 05:57
  • @MusicLovingIndianGirl: the link which u gave accepts `.` decimal. I dont want that.. – Nad May 12 '16 at 05:57
  • it's working fine. I can't insert dot. – Avinash Raj May 12 '16 at 05:58
  • @AvinashRaj: I checked this link http://jsfiddle.net/9U2Mw/5/ which is accepting `.` from the post – Nad May 12 '16 at 05:59
  • try `var regex = /^[+-]?\d+$/;` – Avinash Raj May 12 '16 at 05:59
  • @AvinashRaj: working when i try to enter `.` but it is not working when I copy paste `.` What to do in that condition if user try to copy paste ? – Nad May 12 '16 at 06:01
  • check this http://jsfiddle.net/9U2Mw/714/ – Avinash Raj May 12 '16 at 06:03
  • @AvinashRaj: Working when I try to insert `.` but I am still able to copy paste `.` – Nad May 12 '16 at 06:05
  • how you copy paste? through mouse? then you need to look at mouse listeners – Avinash Raj May 12 '16 at 06:06
  • @AvinashRaj: no not through mouse, through keyboard, When I copy from notepad and I paste into the textbox. It still accepts `.` – Nad May 12 '16 at 06:08
  • @AvinashRaj: any help on this ? why it is not working ? – Nad May 12 '16 at 06:20

1 Answers1

1

I tried you JS Fiddle that is working fine with Firefox, IE and chrome browsers. then i tried this with JQuery with same regex that is working fine.

$("#onlyNumber").on('keypress keyup blur', function(){
     $(this).val($(this).val().replace(/[^\d].+/, ""));
        if ((event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Number Only</label>
<input type='textbox' id='onlyNumber'>
Sourabh
  • 644
  • 1
  • 7
  • 14