#c# #asp.net #html
#c# #asp.net #HTML
Вопрос:
под тегом script мне нужно включить коды для «значение должно быть неотрицательным» при вводе отрицательного числа. я уже включил коды для «значение должно быть числом».
<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>
Ответ №1:
Вы можете проверить первый символ строки, он будет «-«, если это отрицательное число.
Используйте это:
var negative = "-1234";
if (negative[0] == '-')
MessageBox.Show("Negative Number");
или добавьте в свой код:
while (x < teststring.length) {
if (x == 0 amp;amp; 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 amp;amp; teststring.charAt(x) == '-')
{
MessageBox.Show("Negative Number - Stopping loop");
break;
}
Ответ №2:
Попробуйте,
<script type="text/javascript">
function isNumber(n) {
return !isNaN(parseFloat(n)) amp;amp; 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>