如何判断文本输入的必须是数字才能有效呢
写一个明确的方法出来
写一个明确的方法出来
解决方案 »
- 防止安装程序被卸载,怎么做??
- WebBrowser(wpf)如何获取元素背景
- 如何在picturebox上取消最后一次所画的图呢
- 服务器已拒绝客户端凭据 remoting远程连接
- 用HttpWebRequest取远程文件的大小为什么返回值为-1?
- 如何用ICSharpCode做出自解压的zip呢
- Twain协议 支持把多张图片扫描成一张pdf文件吗
- 提问:单击DataGrid某行触发什么事件,我想单击某行后非DataGrid的TextBox得到某行的部分数据
- ModalPopupExtender模式窗口问题
- 请问怎样可以做出像Visual C# .Net 工具中那样的菜单???
- “System.Array”并不包含对“length”的定义出错!!!
- 小问题2个
string str="xxx";
if(int.TryParse(str,out n))
{
//为数字
}
else
{
//非数字
}
Regex rg=new Regex(pat);
Match mh=rg.Match(textBox1.Text);
if(mh.Success)
{
//是汉字
}
2、function fucCheckNUM(NUM)
{
var i,j,strTemp;
strTemp="0123456789.";
if ( NUM.length== 0)
return 0
for (i=0;i<NUM.length;i++)
{
j=strTemp.indexOf(NUM.charAt(i));
if (j==-1)
{
//说明有字符不是数字
return 0;
}
}
//说明是数字
return 1;
}
2003好像只有int.Parse()
那就用try捕获一下异常
{
int.parse(输入的字符串);
}
catch(Exception e)
{
非数字……
}
string str="xxx";
if(int.TryParse(str,out n))
{
//为数字
}
else
{
//非数字
}
如果是第一种的话要用正则表达式或一个一个字符判断,但是如果是VS2005的话,可以设置textbox的checknum属性
如果是后面的话,同意Zine_Alone(老鼠都给猫当伴娘了.哎.)
{
if(str==string.Empty||string==null)
retrun false;
try
{
decimal.Parse(str)
}
catch
{
return false;
}
return true;
}
{
Regex regex = new Regex("[^0-9]");
return !regex.IsMatch(strNumber);
}
if(reg1.IsMatch(str))
{
//数字
}
else
{
//非数字
}
string s = "123456789012345678999999999999999999999999999999999999999999999999999999";
文本s 都是数字,但你能用int.Parse吗?
VB.net有现成的函数IsNumber()If IsNumber("123.234") Then ... 'True
If IsNumber("1a") Then .. 'False
If IsNumber("$100") Then ... 'True
If IsNumber("1.234E+10") Then .. 'True ...
function isNumber(str)
{
var patrn = /^[0-9]{1,20}$/;
var num = patrn.test(str);
if(!num)
{
alert("请输入数字!");
}
}
{
string aa="4578hhh2214";
if(TsNum(aa))
{
System.Console.WriteLine("aaaaaa");
}
else
{
System.Console.WriteLine("bbbbbbb");
}
System.Console.ReadLine();
} public static bool TsNum(string aa)
{
foreach(char st in aa)
{
if(!Char.IsNumber(st))
{
return false;
}
}
return true;
}
{
if( !char.IsNumber( c ) )
{
textBox1.Text = str.Replace( c.ToString(), string.Empty );
textBox1.SelectionStart = textBox1.Text.Length;
}
}
/// 判断是否为整数。是返回true 否返回false。可以传入null。
/// </summary>
/// <param name="strVal">要判断的字符</param>
/// <returns></returns>
public static bool IsInt(string strVal)
{
if (strVal == null || strVal.Length == 0)
return false;
//判断是否只有.、-、 -.
if (strVal == "." || strVal == "-" || strVal == "-.")
return false; //去掉第一个负号,中间是不可以有负号的
if (strVal.Substring(0,1) == "-")
strVal = strVal.Remove(0,1); foreach(char c in strVal)
{
if (c < '0' || c > '9')
return false;
}
return true;
}
/// 判断是否是实数,是返回true 否返回false。可以传入null。
/// </summary>
/// <param name="strVal">要验证的字符串</param>
/// <returns></returns>
public static bool IsNumeric(string strVal)
{
//System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex("-?([0]|([1-9]+\\d{0,}?))(.[\\d]+)?$");
//return reg1.IsMatch(strVal);
//string tmp="";
//判断是否为null 和空字符串
if (strVal == null || strVal.Length == 0)
return false;
//判断是否只有.、-、 -.
if (strVal == "." || strVal == "-" || strVal == "-.")
return false; //记录是否有多个小数点
bool isPoint = false; //是否有小数点
//去掉第一个负号,中间是不可以有负号的
if (strVal.Substring(0,1) == "-")
strVal = strVal.TrimStart('-'); foreach(char c in strVal)
{
if (c =='.')
if (isPoint)
return false;
else
isPoint = true;
if ((c < '0' || c > '9') && c != '.')
return false;
}
return true;
} 效率最高的。
判断日期,VB.net有现成的IsDate函数
就像 "3/8/08","2/15/2002","2002 2 28","2月28日2002年","2月2002年28日","2002年2月28日,"2002-2-28","Oct 9 2008","2006/Feb/20" 这些格式,IsDate函数均可以将其转换成正确的日期并且加以判断。例:
[VB.net]
If IsDate("3/8/07") Then .... ' True。函数将它识别为2007年3月8日
If IsDate("2月2002年28日") Then. ' True。函数将它识别为2002年2月28日
If IsDate("2/29/2001") Then ... ' False。因为2001年的2月没有29日
If IsDate("Oct-9-2008") Then... ' True。函数将它识别为2008年10月9日可见这个函数的复杂性,不但涉及到区域文化问题,还设涉及到的长短格式等问题。
这个功能如果用C#实现 肯定能把人累出屎来^-^.
{
public static void Main()
{
string temp;
temp = Console.ReadLine();
if (Microsoft.VisualBasic.Information.IsDate(temp))
Console.WriteLine("It's a date.");
else Console.WriteLine("It isn't a date.");
if (Microsoft.VisualBasic.Information.IsNumeric(temp))
Console.WriteLine("It's a number.");
else Console.WriteLine("It isn't a number.");
}
} 如何导入dll就不用说了吧.....
datatime.tryParse()
.....
.net2.0中新增加的东西,这个是最简单的转换方法,而且速度比较快。
System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[-]?\d+[.]?\d*$");
if(reg1.IsMatch(str))
{
//数字
}
else
{
//非数字
}
{
if (null == obj) return false; foreach (char ch in obj.ToString())
if (!char.IsDigit(ch)) return false; return true;
}
private bool NumbersCheck(string strNumbers)
{
Regex regex = new Regex("^[0-9]*$");
bool blnCheck = regex.IsMatch(strNumbers);
return blnCheck;
}
//
// 摘要:
// 指示指定字符串中位于指定位置处的字符是否属于十进制数字类别。
//
// 参数:
// s:
// System.String。
//
// index:
// s 中的字符位置。
//
// 返回结果:
// 如果 s 中位于 index 处的字符是十进制数字,则为 true;否则,为 false。
//
// 异常:
// System.ArgumentOutOfRangeException:
// index 小于零或大于 s 中的最后一个位置。
//
// System.ArgumentNullException:
// s 为 null。
public static bool IsDigit(string s, int index);
if(char.IsDigit(e.KeyChar))
{
e.Handled = false;
}
else
{
e.Handled = true;
}或
if(!char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
public int ToInt(object data)
{
if( Regex.IsMatch( data.ToString(), @"^\-?\d{1,9}$" ) )
{
return Convert.ToInt32( data );
}
else
{
return 0;
}
}
// 转化为double型
public double ToDouble( object data )
{
if( Regex.IsMatch( data.ToString(), @"^\-?\d+[\.\d+]?$" ) )
{
return Convert.ToDouble( data );
}
else
{
return 0;
}
}
decimal result = 0;
if(decimal.TryParse(s, out result))
......2.sealeft 说的方法,正则表达式,这种方法通用性强,但不如方法1
if(System.Text.RegularExpressions.Regex.IsMatch(s, @"^[-]?\d+[.]?\d*$"))
......3.char.IsNumber or char.IsDigit,注意要加 '.' 号的判断,这种方法可支持任意长度字符串,效率未必差
private bool IsNumeric(string s)
{
foreach (char c in s)
{
if (c != '.' && !char.IsDigit(c))
{
return false;
}
}
return true;
}4.用 VB 提供的方法,添加引用 Microsoft.VisualBasic,这种方法简单易用
if(Microsoft.VisualBasic.Information.IsNumeric(s))
......
日期的判断是类似的
1.
DateTime result = 0;
if(DateTime.TryParse(s, out result))
......2.
if(System.Text.RegularExpressions.Regex.IsMatch(s, @"^(\d{4})\-(\d{1,2})\-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$");)
......3.
if(Microsoft.VisualBasic.Information.IsDate(s))
......btw: C# Coder 觉得 VB 有不错的方法尽管拿来用就是了,编译后都一样的,不必拘泥于门派之见,何况都是 .NET 一门,最多就是剑宗气宗罢了
{
for (int i=0; i<number.GetLength(); i++) {
if (( number[i]<'0') || (number[i]>'9')) {
return -1;
}
}
return 0;
}
{
if (str==null || str.Length==0)
return false;
foreach(char c in str)
{
if (!Char.IsNumber(c))
{
return false;
}
}
return true;
}
{
if( !char.IsNumber( c ) )
{
textBox1.Text = str.Replace( c.ToString(), string.Empty );
textBox1.SelectionStart = textBox1.Text.Length;
}
}方法太多了
用正则表达式使用Try不好,会导致时间很长 #region 校验字串是否是数字
/// <summary>
/// 校验字串是否是数字
/// </summary>
/// <param name="numberString"></param>
/// <returns>bool</returns>
public static bool IsNumeric(string numberString)
{
try
{
Regex rCode = new Regex(@"^[-+]?\d+(\.\d+)?$");
if (!rCode.IsMatch(numberString))
{
return false;
}
else
{
return true;
}
}
catch (Exception ex)
{
throw ex;
}
} public int myfun(object x)
{
if (x == null || Convert.IsDBNull(x))
{
return 0;
}
else
{
switch (x.GetType().FullName)
{
case "System.String":
Regex rCode = new Regex(@"^-?\d+$"); if (!rCode.IsMatch(x.ToString()))
{
return 0;
}
else
{
return int.Parse(x.ToString());
}
case "System.Int32":
return int.Parse(x.ToString());
default:
return 0;
}
}
} #endregion
楼主的问题很宽,数字的范围还是很大的,整数、小数,小数位数都涉及到,这里给出一种方法,涉及到了数字长度、小数位数等:
public static bool VRegex(String value)
{
Regex reg = new Regex(@"^(([0])|([1-9]\d{0,23}))(\.\d{1,5})?$");
if (reg.IsMatch(value))//reg.Match(value);
return true;
return false;
}
/// <summary>
/// 验证输入的数据是否为合法十进制数字
/// </summary>
/// <param name="str">需要验证的字符串</param>
/// <param name="errorMessage">错误信息</param>
/// <returns></returns>
private static bool ValidDecmail(string str,out string errorMessage)
{
if (str.Length>0)
{
bool bol = false; //为true时表示存在1个以上小数点 System.Text.ASCIIEncoding asc=new System.Text.ASCIIEncoding();
byte[] arrbyte=asc.GetBytes(str); for (int j=0;j<arrbyte.Length;j++)
{
if (arrbyte[j]>57 || arrbyte[j]<48)
{
if (arrbyte[j]==46)
{
if (bol)
{
errorMessage = "格式错误!存在多个小数点!";
return false;
}
else
{
bol = true;
}
}
else
{
errorMessage = "格式错误!应输入十进制数字!";
return false;
}
}
} errorMessage="";
return true; }
else
{
errorMessage="";
return true;
}
}
{
double result;
IConvertible convertible = Expression as IConvertible;
if (convertible == null)
{
char[] chArray = Expression as char[];
if (chArray == null)
{
return false;
}
Expression = new string(chArray);
}
TypeCode typCode = convertible.GetTypeCode();
if ((typCode != TypeCode.String) && (typCode != TypeCode.Char))
{
return IsOldNumericTypeCode(typCode);
}
string text = convertible.ToString(null);
try
{
long num2;
if (Utils.IsHexOrOctValue(text, ref num2))
{
return true;
}
}
catch (StackOverflowException exception)
{
throw exception;
}
catch (OutOfMemoryException exception2)
{
throw exception2;
}
catch (ThreadAbortException exception3)
{
throw exception3;
}
catch (Exception)
{
return false;
}
return DoubleType.TryParse(text, ref result);
}internal static bool IsOldNumericTypeCode(TypeCode TypCode)
{
switch (TypCode)
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
return false;
}
{
数字
}
else
{
非数字
}所有异常由调用者处理才是最合适的。
用e的属性,判断ASCII码
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if(char.IsNumber(e.KeyChar))
{
e.Handled = false;
}
else
{
//其他的輸入則僅允許Backspace有作用
if( e.KeyChar != ((char)8) )
e.Handled = true;
}
}
private bool isNum(string keyChar)
{
int i = 0;
char c;
for (i = 0; i < keyChar.Length; i++)
{
c = keyChar[i];
if (!(c >= 48 && c <= 57))
{
return false;
}
}
return true;
}判断是否只含小数点和数字
private bool isDecimalNum(string keyChar)
{
int i = 0;
char c;
for (i = 0; i < keyChar.Length; i++)
{
c = keyChar[i];
if (!(c >= 48 && c <= 57 || c == 46))
{
return false;
}
}
return true;
}
//判断是否只含数字
private bool isNum(string str)
{
Regex r = new Regex("^[0-9]*$");
Match m = r.Match(str);
if (m.Success)
{
return true;
}
else
{
return false;
}
}
前两种方法可扩展性比较好,你对着ascii表想让输入哪个就加上它的ascii码就得了,后一种方法比较华丽,你学会后可以拿着去显摆一下
bool blnCheck = regex.IsMatch(strNumbers);
正则,我也是这么用的
{
Regex regex = new Regex("[^0-9]");
return !regex.IsMatch(strNumber);
}
{
//不是带有两位小数的数字;
}
/// 是否是小数
/// </summary>
/// <param name="str">检测的对象</param>
/// <returns></returns>
public bool IsDouble(string str)
{
if (str == "+" || str == "-" || str == ".")
{
return false;
}
if (str.Length > 1)
{
if (str.IndexOf('+', 1) != -1)
{
return false;
}
if (str.IndexOf('-', 1) != -1)
{
return false;
}
if (str.IndexOf('.') != -1)
{
if (str.IndexOf('.', str.IndexOf('.') + 1) != -1)
{
return false;
}
}
}
for (int i = 0; i < str.Length; i++)
{
if (str[i] > '9' || str[i] < '0' && str[i] != '.' && str[i] != '+' && str[i] != '-')
{
return false;
}
}
return true;
}
/// <summary>
/// 是否是整数
/// </summary>
/// <param name="str">检测的对象</param>
/// <returns></returns>
public bool IsInt(string str)
{
if (str == "+" || str == "-" || str == ".")
{
return false;
}
if (str.Length > 1)
{
if (str.IndexOf('+', 1) != -1)
{
return false;
}
if (str.IndexOf('-', 1) != -1)
{
return false;
}
if (str.IndexOf('.', 1) != -1)
{
return false;
}
}
for (int i = 0; i < str.Length; i++)
{
if (str[i] > '9' || str[i] < '0' && str[i] != '+' && str[i] != '-')
{
return false;
}
}
return true;
}
/// <summary>
/// 是否是数字
/// </summary>
/// <param name="str">检测的对象</param>
/// <returns></returns>
public bool isNum(string str)
{
if (str == "+" || str == "-")
{
return false;
}
for (int i = 0; i < str.Length; i++)
{
if (str[i] > '9' || str[i] < '0')
{
return false;
}
}
return true;
} /// <summary>
/// (')字符转换('')
/// </summary>
/// <param name="str">转换的对象</param>
/// <returns></returns>
public string InputTrans(string str)
{
str = str.Replace("'", "''");
return str;
}
var d=c.match(/^(-|\+)?\d+$/);
if(d==null)
{
alert("对不起,工作号必须是整数!!");
return false;
}
public static bool IsNumeric(object Expression)
{
double num1;
IConvertible convertible1 = Expression as IConvertible;
if (convertible1 == null)
{
char[] chArray1 = Expression as char[];
if (chArray1 != null)
{
Expression = new string(chArray1);
}
else
{
return false;
}
}
TypeCode code1 = convertible1.GetTypeCode();
if ((code1 != TypeCode.String) && (code1 != TypeCode.Char))
{
return Information.IsOldNumericTypeCode(code1);
}
string text1 = convertible1.ToString(null);
try
{
long num2;
if (Utils.IsHexOrOctValue(text1, ref num2))
{
return true;
}
}
catch (StackOverflowException exception1)
{
throw exception1;
}
catch (OutOfMemoryException exception2)
{
throw exception2;
}
catch (ThreadAbortException exception3)
{
throw exception3;
}
catch (Exception)
{
return false;
}
return DoubleType.TryParse(text1, ref num1);
}
Dim num1 As Double
Dim convertible1 As IConvertible = TryCast(Expression,IConvertible)
If (convertible1 Is Nothing) Then
Dim chArray1 As Char() = TryCast(Expression,Char())
If (Not chArray1 Is Nothing) Then
Expression = New String(chArray1)
Else
Return False
End If
End If
Dim code1 As TypeCode = convertible1.GetTypeCode
If ((code1 <> TypeCode.String) AndAlso (code1 <> TypeCode.Char)) Then
Return Information.IsOldNumericTypeCode(code1)
End If
Dim text1 As String = convertible1.ToString(Nothing)
Try
Dim num2 As Long
If Utils.IsHexOrOctValue(text1, num2) Then
Return True
End If
Catch exception1 As StackOverflowException
Throw exception1
Catch exception2 As OutOfMemoryException
Throw exception2
Catch exception3 As ThreadAbortException
Throw exception3
Catch exception7 As Exception
Return False
End Try
Return DoubleType.TryParse(text1, num1)
End Function