Andrew Kilburn Andrew Kilburn - 6 months ago 19
jQuery Question

How to check if a string is an int?

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?

Answer

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>

Comments