如何驗(yàn)證文本框中的內(nèi)容是否為數(shù)字,本文提供了三種方法,希望對(duì)大家的學(xué)習(xí)有所啟發(fā)。
在某些情況下可能需要讓文本框中的內(nèi)容只能夠輸入數(shù)字,例如手機(jī)號(hào)碼或者郵編之類的,下面簡(jiǎn)單介紹一下如何實(shí)現(xiàn)此功能。
下面是驗(yàn)證數(shù)字的正則表達(dá)式:
"^//d+$" //非負(fù)整數(shù)(正整數(shù) + 0) "^[0-9]*[1-9][0-9]*$" //正整數(shù) "^((-//d+)|(0+))$" //非正整數(shù)(負(fù)整數(shù) + 0) "^-[0-9]*[1-9][0-9]*$" //負(fù)整數(shù) "^-?//d+$" //整數(shù) "^//d+(" //非負(fù)浮點(diǎn)數(shù)(正浮點(diǎn)數(shù) + 0) "^(([0-9]+//.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*//.[0-9]+)|([0-9]*[1-9][0-9]*))$" //正浮點(diǎn)數(shù) "^((-//d+(" //非正浮點(diǎn)數(shù)(負(fù)浮點(diǎn)數(shù) + 0) "^(-(([0-9]+//.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*//.[0-9]+)|([0-9]*[1-9][0-9]*)))$" //負(fù)浮點(diǎn)數(shù) "^(-?//d+)(" //浮點(diǎn)數(shù)
用js判斷文本框輸入的內(nèi)容是否是數(shù)字:
<script language="javascript"> function chkads() { if (lf_addstu.sname.value=="") { alert("姓名不能為空."); lf_addstu.sname.select(); return false; } if (lf_addstu.tpl.value=="") { alert("聯(lián)系電話不能為空."); lf_addstu.tpl.select(); return false; } if(!IsNum(lf_addstu.tpl.value)){ alert("請(qǐng)輸入數(shù)字!") lf_addstu.tpl.focus(); return false; } } function IsNum(num){ var reNum=/^/d*$/; return(reNum.test(num));}</script> <form style="padding:0; margin:0" action="" method="post" onSubmit="return chkads()" id="lf_addstu" name="lf_addstu"> 姓名<br /> <input name="sname" type="text" /><br /> 詳細(xì)地址<br /> <input name="adress" type="text" /><br /> 郵編<br /> <input name="codes" type="text" /><br /> 聯(lián)系電話<br /> <input name="tpl" type="text" /><br /> E-mail<br /> <input name="email" type="text" /> <input type="image" src="img/wanhui06.jpg" </form>
如何判斷輸入文本框是值是否是數(shù)字?
單純的判斷是否是正整數(shù),可使用char.IsDigh(string,int index)和IsNumber(string,int index)函數(shù)
protected void Button2_Click(object sender, EventArgs e) { //判斷正整數(shù) int j=0; for (int i = 0; i < TextBox1.Text.Length; i++) { if (char.IsNumber(TextBox1.Text, i))//這個(gè)方法用來(lái)判斷整數(shù)還可以,判斷負(fù)數(shù)和小數(shù)就失效了 j++; } if (j == TextBox1.Text.Length) { Response.Write("ok"); } else { Response.Write ("no");} }
但是,出現(xiàn)負(fù)數(shù)或者小數(shù)的時(shí)候,以上方法失效,則,使用自定義功能函數(shù)
public bool IsNumber( object obj) { bool result = true; try { string str = obj.ToString(); double d ; d = double.Parse(str); } catch { //parse 函數(shù)進(jìn)行轉(zhuǎn)換,不成功則拋出異常 result = false; } return result; } protected void Button3_Click1(object sender, EventArgs e) { //判斷數(shù) if (IsNumber(TextBox1.Text)) { Response.Write("是數(shù)字"); } else { Response.Write("不是數(shù)字"); } }
以上就是驗(yàn)證文本框中的內(nèi)容是否為數(shù)字的方法,希望對(duì)大家的學(xué)習(xí)有所幫助。