C# 验证参数
在脚本标记下,我需要包含代码,以便在输入负数时,值必须为非负数。我已经包含了值必须是数字的代码C# 验证参数,c#,asp.net,html,C#,Asp.net,Html,在脚本标记下,我需要包含代码,以便在输入负数时,值必须为非负数。我已经包含了值必须是数字的代码 <script type="text/javascript"> function test_ifinteger(testcontrol, nameoffield) { var x = 0; var isok = true; var teststring = testcontrol.value; if (teststring.length
<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>
您可以检查字符串的第一个字符,如果它是负数,它将是 使用以下命令:
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++;
试试看
if (x == 0 && teststring.charAt(x) == '-')
{
MessageBox.Show("Negative Number - Stopping loop");
break;
}
<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>