2015-07-20 24 views
0

我有一個小的,如果我只想檢查一個字符串,看它是否是一個整數。我正在使用JQuery來做到這一點。如何檢查字符串是否爲int?

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; 
        } 

它不工作,任何人可以幫助我,告訴我爲什麼?

+0

是什麼'intRegex' –

+0

@ArunPJohny對不起,意識到我忘了補充它,它現在又增加了 –

+0

@nikhil嗨,這沒有工作或者 –

回答

2

intRegex是一個正則表達式對象,以便調用測試方法,該方法將返回true是字符串滿足正則表達式

$('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>

+0

嗨,我推測你的意思是'測試'的方法?這沒有奏效,因爲它還沒有達到我的戒備。 –

+0

@AndrewKilburn查看更新 –

+0

@ArunPJohny'intRegex.text('應該'測試(' – Tushar

0
var ex=/^[0-9]*$/; 
var A=$('#txtGRCSelect').val(); 
if(ex.test(A)==true) 
{ 
alert("Value integer."); 
} 
0

方法1

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

方法2

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

例如:

IsNumeric(1)