判断文本框输入的内容是否为数字

验证数字的正则表达式:

"^\\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+)("         //浮点数

扫描二维码关注公众号,回复: 4597059 查看本文章

如何判断输入文本框是值是否是数字?

单纯的判断是否是正整数,可使用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("不是数字"); }

猜你喜欢

转载自blog.csdn.net/qq_38819293/article/details/81570887
今日推荐