Check for Integer Only

snow_04
Giga Contributor

Hi,

We have a requirement to check that the value entered in a Text Box is a Integer only i.e. No characters should be allowed to be entered.

This is what I have tried so far:

HTML:

<input type = "textbox" id="test" ng-model="c.test" ng-change="c.checkint()">

 

Client Controller:

c.checkint = function()

{

var num = c.test;

var reg = /^\d+$/;

if(!reg.test(num))

{

alert('Enter Integer only');

}

}

 

Issue is even if numbers are entered it gives me the alert message i.e. allowing both Characters and Integers to be entered. Is there a way we can do this in Service portal widget i.e. allowing only numbers to be entered and if character is entered should throw an alert and clear the input text.

 

7 REPLIES 7

Jon Barnes
Kilo Sage

try using this regular expression if you only want integer input:

/^[0-9]*$/

Hi Jon,

 

Thank you very much for your input. It worked fine for me. One more suggestion I need is when it is a non integer it gives me the alert correctly and then I am making the input field as empty. But is there a way we can just remove the string character and not wiping out the entire field?

 

 

Yeh, you can use replace to do that. Just put this in your function: c.test = c.test.replace(/\D/g, “”); Or c.test = c.test.replace(/^[0-9]/g, “”);

Dylan Mann1
Giga Guru

If you don't want to use regex you can use the isNaN() method, which returns a boolean based on whether it's input is or is not a number. 

if(isNaN(num)) {
  alert('Enter Integer only');
  c.test = "";
}