2011-10-02 77 views
0

下腳本標記我需要包括代碼爲「值必須是非負」輸入負數時輸入。我已經包含了「值必須是數字」的代碼。驗證參數

<script type="text/javascript"> 
    function test_ifinteger(testcontrol, nameoffield) { 
     var x = 0; 
     var isok = true; 
     var teststring = testcontrol.value; 
     if (teststring.length == 0) 
      return true; 
     else { 
      while (x < teststring.length) { 
       if (teststring.charAt(x) < '0' || teststring.charAt(x) > '9') 
        isok = false; 
       x++; 
      } //end while 
      if (!isok) { 
       alert(nameoffield + " must be a number!"); 
       testcontrol.focus(); 
      } //end else if(ok) 
      return isok; 

     }//end else if (teststring.length==0) 
    } //end function 

</script> 

回答

0

您可以檢查字符串的第一個字符,如果它是負數,它將是「 - 」。

使用此:

var negative = "-1234"; 

    if (negative[0] == '-') 
     MessageBox.Show("Negative Number"); 

或添加到您的代碼:

while (x < teststring.length) { 
      if (x == 0 && teststring.charAt(x) == '-') 
       MessageBox.Show("Negative Number - Do what you want"); 
      if (teststring.charAt(x) < '0' || teststring.charAt(x) > '9') 
       isok = false; 
      x++; 

而且,如果它的陰性或不是一個數字,可以考慮打破循環,以避免不必要的循環迭代。 使用「break」命令。

if (x == 0 && teststring.charAt(x) == '-') 
{ 
    MessageBox.Show("Negative Number - Stopping loop"); 
    break; 
} 
0

嘗試,

<script type="text/javascript"> 
function isNumber(n) { 
    return !isNaN(parseFloat(n)) && isFinite(n); 
} 
function test_ifinteger(testcontrol, nameoffield) { 

     var teststring = testcontrol.value; 
     if(isNumber(teststring)) { 
     var no=parseFloat(teststring); // or use parseInt 
     if(no<0) { 
      //negative 
     } 
     } 
     else { 
     //not a number 
     } 
} 
</script>