0

I have a small if where I'd just like to check a string to see if it is an integer. I am using JQuery to do this.

JQUERY:

 var intRegex = /[0-9 -()+]+$/;


 if ($('#txtGRCSelect').val() != '' && intRegex($('#txtGRCSelect').val())) {
                        alert("No CASE");
                        $("#ErrorBoxText").html("Error : A Role has not been selected.");
                        rt = true;
                    }

It doesn't work, can anybody help me and tell me why?

Suman Banerjee
  • 1,923
  • 4
  • 24
  • 40
Andrew Kilburn
  • 2,251
  • 6
  • 33
  • 65

3 Answers3

2

intRegex is a regex object so call the test method which will return true is the string satisfies the regex

$('button').click(function() {
  var intRegex = /^[0-9 -()+]+$/; //may have to add `^` at the beginning to check the string is completely matches the regex, else it will just test whether the string ends with the given characters
  if ($('#txtGRCSelect').val() == '' || !intRegex.test($('#txtGRCSelect').val())) {
    alert("No CASE");
    $("#ErrorBoxText").html("Error : A Role has not been selected.");
    rt = true;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="txtGRCSelect" />
<button>Test</button>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0
var ex=/^[0-9]*$/;
var A=$('#txtGRCSelect').val();
if(ex.test(A)==true)
{
alert("Value integer.");
}
Suman Banerjee
  • 1,923
  • 4
  • 24
  • 40
0

Method 1

function IsNumeric(x){    
var patt = new RegExp("^[0-9]+$");    
return patt.test(x);
}

Method 2

function IsNumeric(x){
x=x.replace('.','#');
return!isNaN(parseFloat(x))&&isFinite(x);
}

example:

IsNumeric(1)
Sarath Ak
  • 7,903
  • 2
  • 47
  • 48