判斷文字框輸入的內容是否為數字
驗證數字的正則表示式:
"^\\d+$" //非負整數(正整數 + 0)
"^[0-9]*[1-9][0-9]*$" //正整數
"^((-\\d+)|(0+))$" //非正整數(負整數 + 0)
"^-[0-9]*[1-9][0-9]*$" //負整數
"^-?\\d+$" //整數
"^\\d+(" //非負浮點數(正浮點數 + 0)
"^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$" //正浮點數
"^((-\\d+(" //非正浮點數(負浮點數 + 0)
"^(-(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*)))$" //負浮點數
"^(-?\\d+)(" //浮點數
如何判斷輸入文字框是值是否是數字?
單純的判斷是否是正整數,可使用char.IsDigh(string,int index)和IsNumber(string,int index)函式
protected void Button2_Click(object sender, EventArgs e)
{
//判斷正整數
int j=0;
for (int i = 0; i < TextBox1.Text.Length; i++)
{
if (char.IsNumber(TextBox1.Text, i))//這個方法用來判斷整數還可以,判斷負數和小數就失效了
j++;
}
if (j == TextBox1.Text.Length)
{
Response.Write("ok");
}
else
{ Response.Write ("no");}
}
但是,出現負數或者小數的時候,以上方法失效,則,使用自定義功能
public bool IsNumber( object obj)
{
bool result = true;
try
{
string str = obj.ToString();
double d ;
d = double.Parse(str);
}
catch
{ //parse 函式進行轉換,不成功則丟擲異常
result = false;
}
return result;
}
protected void Button3_Click1(object sender, EventArgs e)
{
//判斷數
if (IsNumber(TextBox1.Text))
{
Response.Write("是數字");
}
else
{ Response.Write("不是數字"); }