2

when using

<input type="number" name="phoneno" class="required number" minlength="10" maxlength="15" id="ph" /> 

it accepts floating point number also. How to use this to prevent the text box to accept other than integers?

Robert
  • 19,800
  • 5
  • 55
  • 85
Gobi M
  • 3,243
  • 5
  • 32
  • 47

4 Answers4

3

Since you seem to be trying to get a phone number, not a generic number, you probably want to use the tel type of input:

<input type="tel" name="phoneno" class="required number" maxlength="15" pattern="\d{10}" id="ph" />

See MSDN on <input> and its attributes. I’ve removed minlength, since it’s not a valid attribute, but the pattern attribute’s regex requires 10 characters. You can change that regex if you want to be more flexible in the formats of phone numbers you allow – for instance, you could use \d{10}|\d{3}-\d{3}-\d{4}.

The pattern attribute is necessary to actually verify that the text looks like a phone number. The browser does little validation of the contents of tel inputs by default; it mainly just displays a keyboard with numbers to mobile browsers. But you can write a JavaScript regular expression in the pattern attribute for use in validation (as the MSDN page explains).

Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
0

You can use the regex object: ^\d+$ Learn more about regex usage in Javascript Here.

Sunny R Gupta
  • 5,026
  • 1
  • 31
  • 40
0

JQuery solution

html stays at it is

<input type="number" name="phoneno" class="required number" minlength="10" maxlength="15" id="ph" />

Jquery

$(function (){$("#ph").blur(function (){
    var regX = /^\d+$/;  
    if(regX.test($(this).val()) == false) 
    {
      //do something it is not int. In this case clear value and alert message 
      $(this).val('');
      alert("put integer");

    }

   });
});
Robert
  • 19,800
  • 5
  • 55
  • 85
-1

calling this function on kypress event 46 is for decimal point just remove it and you are done.

    function isNumberKey(evt)
    {
   var charCode = (evt.which) ? evt.which : event.keyCode;
   if (charCode != 46 && charCode > 31 
     && (charCode < 48 || charCode > 57)){
       alert("First Contact Number must be a number(0-9) !");
      return false;
   }
   return true;
    }
Gaurav
  • 304
  • 2
  • 6